<?php

/**
* @version 2.6.8
* @package Joomla 1.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

// session_destroy();
if(!class_exists('JConfig')){

	session_start();

}
require_once( JPATH_SITE.'/components/com_dtregister/common.php');
global $now , $month_arr ,$lang_var , $cachequeryresult;
$config =& JFactory::getConfig();
$db = &JFactory::getDBO();
 $dbclass =  get_class($db);
 $code =<<<EOF
 class DT_Dbo extends $dbclass{
     
	 var \$cachequeryresult ;
	 
	 function __construct(){
		  \$this->_debug = true ;
		 \$conf =& JFactory::getConfig();
	     \$host 		= \$conf->getValue('config.host');
		 \$user 		= \$conf->getValue('config.user');
		 \$password 	= \$conf->getValue('config.password');
		 \$database   		= \$conf->getValue('config.db');
		 \$dbprefix 	= \$conf->getValue('config.dbprefix');
		 \$dbtype 	= \$conf->getValue('config.dbtype');
		 \$debug 		= \$conf->getValue('config.debug');
		 \$driver 	= \$conf->getValue('config.dbtype');

				\$options = array("driver"=>\$driver, "host"=>\$host, "user"=>\$user, "password"=>\$password, "database"=>\$database, "prefix"=>\$dbprefix,"select"=>true);
		 parent::__construct(\$options);
	 }
	
	 
	 function loadObjectList(){
		
		 \$query = \$this->getQuery();
		  \$key = md5(str_replace(" ","",\$query));
		  
		 if(isset(\$this->cachequeryresult[\$key])){ 
			 \$data = \$this->cachequeryresult[\$key] ;
		 }else{ 
			  \$data = parent::loadObjectList();
			  //print_r(\$data);
			  \$this->cachequeryresult[\$key] = \$data ;
			 
		 }
		
		return \$data ;
	 }  	
	 
	
   
  }
EOF;

  eval( $code );

//$db = new DT_Dbo();
 
 
   


/*if($config->getValue('config.dbtype')=='mysql' ){
  
}else{
   class DT_Dbo extends JDatabaseMySQL{
  
	 function loadObjectList(){
		$data = parent::loadObjectList();
		return $data ;
	 }  	
   
  }


}*/


jimport('joomla.utilities.date');
$now = new JDate('now');
$config =& JFactory::getConfig();
$now->setOffset($config->getValue('config.offset'));
//define the helper function for encode library
$month_arr =  array (
   
  '01'=>JText::_( 'DT_JAN'),
  '02'=>JText::_( 'DT_FEB'),
	'03'=>JText::_( 'DT_MAR'),
  '04'=>JText::_( 'DT_APR'),
	'05'=>JText::_( 'DT_MAY'),
	'06'=>JText::_( 'DT_JUN'),
	'07'=>JText::_( 'DT_JUL'),
	'08'=>JText::_( 'DT_AUG'),
	'09'=>JText::_( 'DT_SEP'),
	'10'=>JText::_( 'DT_OCT'),
	'11'=>JText::_( 'DT_NOV'),
	'12'=>JText::_( 'DT_DEC'),

);
 $lang_var = array('Paypal'=>JText::_('PAYPAL'),'paypal'=>JText::_('PAYPAL'),'Authorize.net'=>JText::_('AUTH_NET'),'Echeck'=>JText::_('ECHECK'),'Mail'=>JText::_('DT_MAILIN_PAYMENT'),

	'Phone'=>JText::_('DT_CALLIN_PAYMENT'),'At_door'=>JText::_('DT_PAY_AT_DOOR'),'free'=>JText::_('DT_FREE'),'Free'=>'Free',''=>'','Pay Later'=>'',

	'Credit Card (Authorize.net)'=>JText::_('AUTH_NET'),'E-Check (Authorize.net)'=>JText::_('ECHECK'),'ideal'=>JText::_('DT_IDEAL'),'GoogleCheckout'=>JText::_('DT_GOOGLE_CHECKOUT'),'NetDeposit'=>JText::_('DT_NETDEPOSIT'),'Eway'=>JText::_('DT_EWAY'));
if(!function_exists('str_split'))

{

	function str_split($text, $split = 1){

	    $array = array();

	    for($i=0; $i < strlen($text); $i++){

	        $key = NULL;

	        for ($j = 0; $j < $split; $j++){

	        $key .= $text[$i];

	        }

	        array_push($array, $key);

	    }

	    return $array;

	}

}

$conf = &JFactory::getConfig();
$document = & JFactory::getDocument();

$document->addStyleSheet('components/com_dtregister/assets/css/main.css');

$pattern="E:E:R:F:I:E";



require_once( JPATH_SITE.'/components/com_dtregister/class.dtregister.php');

require( JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
error_reporting(1);
//require the encode library
require_once(JPATH_SITE."/components/com_dtregister/encode.class.php");

global $states;

$states = array(

'ALABAMA'=>                     'AL',

'ALASKA'=>                      'AK',

'AMERICAN SAMOA'=>              'AS',

'ARIZONA'=>                     'AZ',

'ARKANSAS'=>                    'AR',

'CALIFORNIA'=>                  'CA',

'COLORADO'=>                    'CO',

'CONNECTICUT'=>                 'CT',

'DELAWARE'=>                    'DE',

'DISTRICT OF COLUMBIA'=>        'DC',

'FEDERATED STATES OF MICRONESIA'=>'FM',

'FLORIDA'=>                         'FL',

'GEORGIA'=>                          'GA',

'GUAM'=>                            'GU',

'HAWAII'=>                     'HI',

'IDAHO'=>                         'ID',

'ILLINOIS'=>                     'IL',

'INDIANA'=>                        'IN',

'IOWA'=>                           'IA',

'KANSAS'=>                           'KS',

'KENTUCKY'=>                         'KY',

'LOUISIANA'=>                        'LA',

'MAINE'=>                           'ME',

'MARSHALL ISLANDS'=>                 'MH',

'MARYLAND'=>                        'MD',

'MASSACHUSETTS'=>                    'MA',

'MICHIGAN'=>                         'MI',

'MINNESOTA'=>                        'MN',

'MISSISSIPPI'=>                      'MS',

'MISSOURI'=>                         'MO',

'MONTANA'=>                         'MT',

'NEBRASKA'=>                        'NE',

'NEVADA'=>                           'NV',

'NEW HAMPSHIRE'=>                    'NH',

'NEW JERSEY'=>                       'NJ',

'NEW MEXICO'=>                       'NM',

'NEW YORK'=>                         'NY',

'NORTH CAROLINA'=>                   'NC',

'NORTH DAKOTA'=>                     'ND',

'NORTHERN MARIANA ISLANDS'=>         'MP',

'OHIO'=>                             'OH',

'OKLAHOMA'=>                         'OK',

'OREGON'=>                          'OR',

'PALAU'=>                            'PW',

'PENNSYLVANIA'=>                     'PA',

'PUERTO RICO'=>                      'PR',

'RHODE ISLAND'=>                    'RI',

'SOUTH CAROLINA'=>                   'SC',

'SOUTH DAKOTA'=>                     'SD',

'TENNESSEE'=>                        'TN',

'TEXAS'=>                            'TX',

'UTAH'=>                            'UT',

'VERMONT'=>                          'VT',

'VIRGIN ISLANDS'=>                   'VI',

'VIRGINIA'=>                         'VA',

'WASHINGTON'=>                       'WA',

'WEST VIRGINIA'=>                    'WV',

'WISCONSIN'=>                       'WI',

'WYOMING'=>                         'WY',

);

//Initial the object

global $ptc;

$ptc=new Protector();

$ptc->Pattern=$pattern;
/*************************************

 * Helper Function list

 * these functions help out the Main functions

 ************************************/

// Format the number

####Restore session from database after paypal return

function session_restore(){

	global $database;

	$database = &JFactory::getDBO();
  $paypal_session_id = 0 ;
	$data = explode('|',$_REQUEST['custom']);
    
	foreach($data as $key=>$value){

		if(substr($value,0,7)=='session'){

			$arr = explode("=",$value);

			$paypal_session_id = $arr[1];

			break;

		}

	}

	 $sql  = "select * from #__dtregister_session where id=$paypal_session_id";

	$database->setQuery($sql);

	 $database->query();

	$row = $database->loadObjectList();

   $data = unserialize($row[0]->data);

	$_SESSION = $data;

	if($row[0]->user_id > 0 && $row[0]->user_id!=""){

		$_REQUEST['userId'] = $row[0]->user_id;

		$_GET['userId'] = $row[0]->user_id;

		$_REQUEST['user_id'] = $row[0]->user_id;

		$_GET['user_id'] = $row[0]->user_id;

	}
    return $paypal_session_id ;
}

//Here are the help functions to compute the available spots for a specific event

function getAvailableSpots($eventId)

{

	$database = &JFactory::getDBO();

	$sql="Select max_registrations From #__dtregister_group_event Where eventId=$eventId";

	$database->setQuery($sql, 0, 1);

	$maxRegistration=$database->loadResult();

	if($maxRegistration<=0)

		return -1;

	else

	{

        $evt = new Event($eventId);

		$registered = $evt->get_registrants();

		if (!$registered)

			$registered=0;

		return $maxRegistration-$registered;

	}

	//Get the number of registrations

}

// loops through all of the group users and saves their info

function saveGroupInfo($option, $eventId){

	global $Itemid, $mainframe;

	$database = &JFactory::getDBO();

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$eventId = $_SESSION['register']['eventId'];

    $dt_event = new Event($eventId );

	$Itemid = $_SESSION['register']['Itemid'];

	$current_member = $_SESSION['register']['current_member'];

 	// array to hold all non-custom fields

	$arrFields = array (
        
		1 	=> array('title', JText::_( 'DT_TITLE' ), 'm_s_title', 'm_r_title',JText::_( 'DT_TITLE')),
		
		2 	=> array('firstname', JText::_( 'DT_FIRSTNAME' ), 'm_s_firstname', 'm_r_firstname',JText::_( 'DT_ENTER_FNAME')),

		3 	=> array('lastname', JText::_( 'DT_LASTNAME'), 'm_s_lastname', 'm_r_lastname',JText::_( 'DT_ENTER_LNAME')),

		4 	=> array('organization', JText::_( 'DT_ORGANIZATION'), 'm_s_organization', 'm_r_organization',JText::_( 'DT_ENTER_ORGANIZATION')),

		5 	=> array('address', JText::_( 'DT_ADDRESS'), 'm_s_address', 'm_r_address',JText::_( 'DT_ENTER_ADDRESS')),
      
        6 	=> array('address2', JText::_( 'DT_ADDRESS2'), 'm_s_address2', 'm_r_address2',JText::_( 'DT_ENTER_ADDRESS2')),
		
		7 	=> array('city', JText::_( 'DT_CITY'), 'm_s_city', 'm_r_city',JText::_( 'DT_ENTER_CITY')),

		8 	=> array('state', JText::_( 'DT_STATE'), 'm_s_state', 'm_r_state',JText::_( 'DT_ENTER_STATE')),

		9 	=> array('zip', JText::_( 'DT_ZIPCODE'), 'm_s_zip', 'm_r_zip',JText::_( 'DT_ENTER_ZIP')),

		10 	=> array('country', JText::_( 'DT_COUNTRY'), 'm_s_country', 'm_r_country',JText::_( 'DT_ENTER_COUNTRY')),

		11 	=> array('email', JText::_( 'DT_EMAIL'), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL')),

		#10 	=> array('cemail', 'DT_CONFIRM_EMAIL', 'm_s_email', 'm_r_email','DT_ENTER_EMAIL'),

		12	=> array('phone', JText::_( 'DT_PHONE'), 'm_s_phone', 'm_r_phone',JText::_( 'DT_ENTER_PHONE'))

	);

	// get the custom Field ID's for this event

	$sql="Select fe.field_id From #__dtregister_field_event as fe inner join #__dtregister_fields as df on fe.field_id=df.id where fe.event_id=$eventId and ((fe.showed in(2,3)) or (fe.showed =-1 and df.showed in(2,3)))";

	$database->setQuery($sql);

	$rows=$database->loadObjectList();

	$arrFieldIds=array();

	for($i=0,$n=count($rows);$i<$n;$i++){

		$arrFieldIds[]=$rows[$i]->field_id;

	}

	// Get the actual custom fields from the previous queries ID

	if(count($arrFieldIds))	{

		$sql="Select * From #__dtregister_fields where id in (". implode(",",$arrFieldIds) .") and published=1 and hidden=0 order by ordering ";

		$database->setQuery($sql);

		if($database->getErrorMsg()){

			echo $database->getErrorMsg();

		}

		$rowCustoms=$database->loadObjectList();

	} else {

		$rowCustoms=null;

	}

	// loop through the post storing values in the SESSION var

	$arrPostVals = array();

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

		$arr = array($value[0]=>$_POST[$value[0]]);

		array_push_associative($arrPostVals,$arr);

	}

		//***************************

		//Get custom fields and store in CustomFields array

  		$arrGetCustom = array();
       $fld = new Custom_field();
			$fields=array() ;
			
            $fld->getAllFields($eventId,'M',false,0,$fields) ;
			
			$rowCustoms = $fields ;
			
		for($i=0,$n=count($rowCustoms);$i<$n;$i++){

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$type=$rowCustom->type;

			$value=JRequest::getVar($name,'','post');

			if($type==3){

				$value=implode('|',$value);

			}

			$val = array($name=>$value);

			#array_push_associative($arrGetCustom,$val);

			array_push_associative($arrPostVals,$val);

		}

		//	Add custom fields fee to amount charged

		for($i=0,$n=count($rowCustoms);$i<$n;$i++){

			$rowCustom=$rowCustoms[$i];
            $name=$rowCustom->name;
			$values=$rowCustom->values;

			$arrValues=explode("|",$values);

			$postedValue=JRequest::getVar($name,'','post');
			if(in_array($rowCustom->type,array(1,3,4))){
			   	
				if(!is_array($postedValue)){
				   	
					$postval = array($postedValue);
			    }else{
					$postval = $postedValue ;
				}
				foreach($arrValues as $key=>$val){
				
				   if(in_array($val,$postval)){
					    if(!isset($_SESSION['register']['option_used'][$rowCustom->id][$key])){
					  
					         $_SESSION['register']['option_used'][$rowCustom->id][$key] = 1 ;
					       
				        }else{
						   	
					          $_SESSION['register']['option_used'][$rowCustom->id][$key]++ ;
						}
				   }
				  
				   	
				}
				
				
			}
			
			if(!$rowCustom->fee_field){ continue; }

			

			$customType=$rowCustom->type;

			
			$fees=$rowCustom->fees;

			$arrFees=explode("|",$fees);

			
			
            
			for($j=0,$m=count($arrValues);$j<$m;$j++){

				if($customType==3){

					if(in_array(trim($arrValues[$j]),$postedValue)){

						$customFee+=$arrFees[$j];

					}

				} else {

					if(trim($arrValues[$j])==$postedValue){

						$customFee+=$arrFees[$j];

						break;

					}

				}

			}

		}
		
        $customFee = $dt_event->get_custom_fields_fee((array)$arrPostVals,'M');
        
		$_SESSION['register']['groupUser'][$current_member]=$arrPostVals;

		$_SESSION['register']['groupUser'][$current_member]['customFee'] = $customFee;
        
	// redirect to register another group user or to billing info
  
	if ($_SESSION['register']['memtot'] > $current_member){

		$current_member++;

		$_SESSION['register']['current_member'] = $current_member;

    $url="index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=get_group_users";
      
		$mainframe->redirect($url);

	} else {
    
    $url="index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_group_billing";

		$mainframe->redirect($url);

	}

}

// Saves the individual and group users info

function insertTable($arrFields,$arrValues,$tableName){
    
    global $now ;
	$database = &JFactory::getDBO();

    $i = 0;
	foreach($arrFields as $arrField){
	  
	   if(isset($arrFields[$i])){
		  $arrFields[$i]=$database->NameQuote($arrFields[$i]);

		  $arrValues[$i]=$database->Quote(stripslashes($arrValues[$i]));
		}
	  
	  $i++;
	}
	
	if ($tableName == '#__dtregister_user'){

		// have to put 'register_date' in here because the value 'NOW()' won't work in an array - php tries to execute it as a function

		$sql="INSERT INTO $tableName(".implode(",",$arrFields).",register_date) VALUES (".implode(",",$arrValues).",'".$now->toMySQL (true)."')";

	} else {

		$sql="INSERT INTO $tableName(".implode(",",$arrFields).") VALUES (".implode(",",$arrValues).")";

	}

	$database->setQuery($sql);

	$database->query();
    
	if($database->getErrorMsg()){

		echo "<br />".$database->getErrorMsg()."<br />";

		return 0;

	}else{

		return $database->insertid();

	}

}

/*

 * registration has been processed, here we save the registration to the DB

 * need to saveInfo from paypal, but if payment is cancelled the user info should be removed

 * 		from all tables... users, group, group_amount

 * Parameters:

 * 		$type = payment method: paypal, credit card, echeck, pay later/free

 * 		$paymentVerified = if payment has been confirmed

*/

function saveInfo($type, $paymentVerified = 0, $confirmNum = NULL){

	global $Itemid ,$mainframe,$thanksemail;
    global $lang_vars ;
	$conf = &JFactory::getConfig();
    $payment_type = $type ;
	$mosConfig_mailfrom = $conf->_registry['config']['data']->mailfrom;

	$mosConfig_fromname =$conf->_registry['config']['data']->fromname;
   
	$mail = &JFactory::getMailer();

	$user = &JFactory::getUser();

	$database = &JFactory::getDBO();

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
    if($confirmNum==""){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$dt_user  = new DT_User();
     $confirmNum = $dt_user->generateconfirmNum();

   	}
	 
	$sqlArray = array();
   
	$eventId 	= $_SESSION['register']['eventId'];
    $dt_evt = new Event($eventId);
	$dt_evt->over_ride_global();
	$Itemid		= $_SESSION['register']['Itemid'];

	$userType 	= $_SESSION['register']['reg_type'];

	if ($userType=='reg_individual'){$userType='I';}else if($userType=='reg_group'){$userType='G';}
	
	if($userType !='I' || $userType !='G'){
	    
		if(isset($_SESSION['register']['groupUser']) && is_array($_SESSION['register']['groupUser']) && count($_SESSION['register']['groupUser']) > 1){
		   $userType  = 'G' ;
		   if($_SESSION['register']['memtot'] == ""){
		     $_SESSION['register']['memtot'] =  count($_SESSION['register']['memtot']);
		   }
		}else{
		   $userType  = 'I' ;
		    if($_SESSION['register']['memtot'] == ""){
		     $_SESSION['register']['memtot'] =  1;
		   }
		}
		
	}

	$arrNonCustom = array('firstname','lastname','organization','address','city','state','zip','phone','email','country','title','address2');

	$title 		= $_SESSION['register']['billingInfo']['title'];
	
	$fname 		= $_SESSION['register']['billingInfo']['firstname'];

	$lname 		= $_SESSION['register']['billingInfo']['lastname'];

	$org 		= $_SESSION['register']['billingInfo']['organization'];

	$address 	= $_SESSION['register']['billingInfo']['address'];

	$city 		= $_SESSION['register']['billingInfo']['city'];

	$state 		= $_SESSION['register']['billingInfo']['state'];

	$zip 		= $_SESSION['register']['billingInfo']['zip'];

	$phone 		= $_SESSION['register']['billingInfo']['phone'];

	$email 		= $_SESSION['register']['billingInfo']['email'];

	$country 	= $_SESSION['register']['billingInfo']['country'];

	$amountCharged = $_SESSION['register']['amountCharged'];

	$customFee 	= $_SESSION['register']['billingInfo']['customFee'];

	$paymentMethod = $_SESSION['register']['paymentMethod'];

	$memtot		= $_SESSION['register']['memtot'];

	$discount_code_amount = $_SESSION['register']['discount_code_amount'];

	$discount_code_id    = ($_SESSION['register']['discount_code_id'])?$_SESSION['register']['discount_code_id']:0;
	
	$transaction_id    = ($_SESSION['register']['billingInfo']['transaction_id'])?$_SESSION['billingInfo']['transaction_id']:'';

	//Get custom fields and store in CustomFields array

	$sql="SELECT f.id , f.name,f.label FROM #__dtregister_fields f, #__dtregister_field_event e WHERE e.field_id=f.id AND e.event_id=$eventId and f.hidden=0 and  (e.showed=1 or (e.showed =2 and f.showed=1))";

	$database->setQuery($sql);

	$rows=$database->loadObjectList();

	$arrCustomFields=array();

	for($i=0,$n=count($rows);$i<$n;$i++){

		$tmparray = array($rows[$i]->name => $rows[$i]->label);

		array_push_associative($arrCustomFields,$tmparray);

	}

	// for the custom email

	$contactDetails = $address.'<br />'.$city.', '.$state.' '.$zip.'<br />'.$phone.'<br />'.$email;

	//$customFee += $_SESSION['register']['billingInfo']['customFee'];

	unset($_SESSION['register']['billingInfo']['customFee']);// this field is not needed for the DB

	$arrMemberFields = array_keys($_SESSION['register']['billingInfo']);

	// these are the fields that need 'user' prepended to them for the DB
   
	$compare = array('firstname','lastname','organization','address','city','state','zip','country','email','phone','title','address2');
    
	foreach ($arrMemberFields as $key=>$value){

		if (in_array($value, $compare)){

			$arrMemberFields[$key] = 'user'. $value;

		}
		if($value=="partial_payment"){
		  unset($arrMemberFields[$key]) ;
		  $partial_key = $key ;
		}

	}
	
	$arrMemberFields[] = 'confirmNum';

	$arrMemberFields[] = 'eventid';

	$arrMemberFields[] = 'usertype';

	$arrMemberFields[] = 'user_id';

	$arrMemberFields[] = 'due_amount';

	$arrMemberFields[] = 'payment_verified';
   
	if ($type == 'pay_later' || $type=="ideal" || $type=='GoogleCheckout' ||  $type == 'Credit Card (Authorize.net)' || $type == 'E-Check (Authorize.net)' || $type == 'Paypal' || $type == 'free'|| $type=='NetDeposit' || $type=='Eway'){

		$arrMemberFields[] = 'payment_type';

		if ($type == 'pay_later'){ $arrMemberFields[] = 'pay_later_option'; }

	}

	$arrMemberValues = array_values($_SESSION['register']['billingInfo']);
    
	if(isset($partial_key)){
	    
		unset($arrMemberValues[$partial_key]);
	}
     
	$arrMemberValues[] = $confirmNum;

	$arrMemberValues[] = $eventId;

	$arrMemberValues[] = $userType;

	$arrMemberValues[] = $user->id;

	$arrMemberValues[] = $amountCharged;
    if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
		   
		   $payment_status = 0 ;
		   // $paymentVerified = 0;
		   
		}
	
	if ($type == 'pay_later'){
        
		$arrMemberValues[] = 0; // payment_verified

		$payLaterOption=JRequest::getVar('pay_later_option',0);

		$paylater_values = array(1=>'At_door',2=>'Mail',3=>'Phone');

		$arrMemberValues[] = $paylater_values[$payLaterOption]; // payment_type

		$type  = $paylater_values[$payLaterOption];

		$arrMemberValues[] = $payLaterOption;

		switch($payLaterOption){

			case '1':

				$payLaterOption = JText::_('DT_PAY_AT_DOOR');

				break;

			case '2':

				$payLaterOption = JText::_('DT_MAILIN_PAYMENT');

				break;

			case '3':

				$payLaterOption = JText::_('DT_CALLIN_PAYMENT');

				break;

		}

	} else if($type == 'Credit Card (Authorize.net)') {

		$arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'Credit Card (Authorize.net)'; // payment_type

	} else if($type == 'E-Check (Authorize.net)') {

		$arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'E-Check (Authorize.net)'; // payment_type

	} else if($type == 'Paypal') {

		$arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'Paypal'; // payment_type

	}else if($type == 'NetDeposit') {

		$arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'NetDeposit'; // payment_type

	}else if($type == 'Eway') {

		$arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'Eway'; // payment_type

	}else if($type=='ideal') { 

      $arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'ideal'; // payment_type

     } else if($type=='GoogleCheckout') { 

      $arrMemberValues[] = $paymentVerified; // payment_verified

		$arrMemberValues[] = 'GoogleCheckout'; // payment_type

     } else {

		$arrMemberValues[] = $paymentVerified; // payment_verified

        $arrMemberValues[] = 'Free'; // payment_type

	}

	$arrMemberFields[] = 'discount_code_id';

   $arrMemberValues[] = $discount_code_id;
   $paylater_values = array(1=>'At_door',2=>'Mail',3=>'Phone');
    if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
	  $arrMemberFields[] = 'pay_later_paid' ;
	   $paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
	   if(($amountCharged+$customFee-$discount_code_amount)>$paid_amount){
	      $paymentVerified = 0 ;
		  $arrMemberValues[] = 0 ;
	   }else{
	      $paymentVerified = 1 ;
		  $arrMemberValues[] = 1;
	   }
	   
	}else{
	   if($type == 'pay_later' || in_array($type,$paylater_values)){
	      $paid_amount = 0;
	   }else{
	      $paid_amount = $amountCharged+$customFee-$discount_code_amount;
	   }
      
	}
	
	if($type == 'pay_later' || in_array($type,$paylater_values)){
	      $paid_amount = 0;
	}
	
	$arrMemberFields[] = 'paid_amount';
	$arrMemberValues[] = str_replace(",",".",$paid_amount) ;
	
	$uid = insertTable($arrMemberFields,$arrMemberValues,'#__dtregister_user');

	if($paymentVerified==1){

		 $sql = "update #__dtregister_user set payment_verified=1 , pay_later_paid=1 where userId=".$uid;

		 $database->setQuery($sql);

			$database->query();

	} 
	 if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
	 
	   $paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
	   
	   if(($amountCharged+$customFee-$discount_code_amount)>$paid_amount){
	       $sql = "update #__dtregister_user set payment_verified=1 , pay_later_paid=0 , cancel=".$partial_default_status." where userId=".$uid;

		 $database->setQuery($sql);
          echo $database->getErrorMsg();
			$database->query();
	   }else{
	     $sql = "update #__dtregister_user set payment_verified=1 , pay_later_paid=1 , cancel=".$paid_default_status." where userId=".$uid;

		 $database->setQuery($sql);

			$database->query();
	   }
	   $paymentVerified = 1;
	}

    if($payment_type == 'pay_later'){
	     $sql = "update #__dtregister_user set payment_verified=1 , pay_later_paid=0 , cancel=".$paylater_default_status." where userId=".$uid;

		 $database->setQuery($sql);

		$database->query();
	}
    //die ;
    $dt_user =  new DT_User($uid,$eventId );
    if(isset($_SESSION['register']['joomlauser'])){
	   $dt_user->userRegistration($_SESSION['register']['joomlauser']['username'],$_SESSION['register']['joomlauser']['password']);
	}
	if($confirm_number_type == 'sequential'){
	    
		$dt_config = new DTConfig();
		$confirm_number_start = $dt_config->getConfig('confirm_number_start');
		$confirm_number_start  = str_replace($confirm_number_prefix,'',$confirmNum);
		$dt_config->setConfig('confirm_number_start',$confirm_number_start);
		
	}
	if($barcode_enable){
	   $barcode = new DTbarcode($confirmNum,$confirmNum);
       $barcode->preview();
	
	}
	
    JPluginHelper::importPlugin( 'dtregister' );

    $mainframe->triggerEvent( 'OnDtregisterRegistration',array($dt_user));
    
	// not for paypal - payment not verified yet

	if ($type != 'Paypal' && $type !="Credit Card (Authorize.net)"){
	   	$paylater_values = array(1=>'At_door',2=>'Mail',3=>'Phone');
        if(in_array($type,$paylater_values)){
		   if($dt_user->event->pay_later_thk_msg_set){
		      $pay_later_thk_msg = $dt_user->event->pay_later_thk_msg;
		   }
		   $thanksmsg = $pay_later_thk_msg ;
		}else{
		   
		   if($dt_user->event->thanksmsg_set){
		      $thanksmsg = $dt_user->event->thanksmsg;
		   }
		  
		}
		
		echo "</form>".stripslashes(parse_tags($thanksmsg,$uid,$eventId)) . '<br /><br />';
		
	}
    
	$sql="INSERT INTO #__dtregister_group(useid) VALUES($uid)";

	$database->setQuery($sql);

	$database->query();

	$gid=$database->insertid();

	// if group registration then save the group users

	if ($userType == 'G'){

		//Insert members data and custom field values

		foreach ($_SESSION['register']['groupUser'] as $key => $value){

			unset($_SESSION['register']['groupUser'][$value]['customFee']);// this field is not needed for the DB

			unset($value['customFee']);// this field is not needed for the DB

			$arrMemberFields = array_keys($value);

			$arrMemberFields[] = 'groupUserId';

			$arrMemberValues = array_values($value);

			$arrMemberValues[] = $gid;

			insertTable($arrMemberFields,$arrMemberValues,'#__dtregister_group_member');

		}
		if(count($_SESSION['register']['groupUser'])){
		   $memtot = count($_SESSION['register']['groupUser']);
		}

	}

	$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	$eventName=$database->loadResult();

	$amount = $amountCharged+$customFee-$discount_code_amount;

		$sql="INSERT INTO #__dtregister_group_amount(groupId,numberOfPerson,amount)VALUES('$gid','$memtot','$amount')";

		$database->setQuery($sql);

		$database->query();

		$subadmin = JText::_('DT_ADMIN_SUBJECT');

		$thanksemail = sprintf($thanksemail,$eventName,$amountCharged);

		if ($userType == 'G'){

			$adminmsg.= $fname . ' ' . $lname . ' ' . JText::_('DT_ADMIN_MESSAGE') . ' ' . $eventName . '.<br /><br />';

		} else {

			$adminmsg.= $fname . ' ' . $lname . ' ' . JText::_('DT_ADMIN_MESSAGE') . ' ' . $eventName . '.<br /><br />';

		}

		$sql="SELECT summary,dtstart,if(noendtime=0,dtend,'') as dtend FROM #__jevents_vevdetail WHERE evdet_id=$eventId";

	$database->setQuery($sql);

		$row = $database->loadObject();

		$eventName=$row->summary;

		$startDate=$row->dtstart;

		$endDate=$row->dtend;

		$start_date =JFactory::getDate($row->dtstart)->toFormat('%b %d, %Y');

		$end_date  = JFactory::getDate($row->dtend)->toFormat('%b %d, %Y');

		$event_date = get_date($row->dtstart,$row->dtend,null,true);

		if($start_date != $end_date ){

			$event_date .= " - ".get_date($row->dtend,null,true);

		}

		$adminmsg.= JText::_('DT_ADMIN_MSG_DETAILS') . ":<br /><br />";

		$adminmsg.="<table>";

		$adminmsg.="<tr><td>".JText::_('DT_EVENT_NAME').": </td><td>".$eventName."</td></tr>";

		$adminmsg.="<tr><td>".JText::_('DT_EVENT_DATE').": </td><td>".$event_date."</td></tr>";

		$adminmsg.="<tr><td>".JText::_('DT_ADMIN_REGISTRANT_NAME').": </td><td> $fname $lname</td></tr>";

		if($org != NULL){$adminmsg.="<tr><td>".JText::_('DT_ORGANIZATION').": </td><td> $org</td></tr>";}

		if($address != NULL){$adminmsg.="<tr><td>".JText::_('DT_ADDRESS').": </td><td> $address</td></tr>";}

		if($city != NULL){

			if($state != NULL){

				$adminmsg.="<tr><td>".JText::_('DT_CITY_STATE').": </td><td> $city ($state, $country)</td></tr>";

			} else {

				$adminmsg.="<tr><td>".JText::_('DT_CITY')." (".JText::_('DT_COUNTRY')."): </td><td> $city ( $country)</td></tr>";

			}

		}

		if($zip != NULL){$adminmsg.="<tr><td>".JText::_('DT_ZIPCODE').": </td><td> $zip</td></tr>";}

		if($phone != NULL){$adminmsg.="<tr><td>".JText::_('DT_PHONE').": </td><td> $phone</td></tr>";}

		$adminmsg.="<tr><td>".JText::_('DT_EMAIL').": </td><td> $email</td></tr>";

		// add custom fields to the message

	$contactCustomFields = "";

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

				if($_SESSION['register']['billingInfo'][$key]==""){

					continue;

				}

				$adminmsg.="<tr><td>".$value.": </td><td>".$_SESSION['register']['billingInfo'][$key]."</td></tr>";

				$contactCustomFields .= $value.': '.$_SESSION['register']['billingInfo'][$key].'<br />';

		}

		$adminmsg.="<tr><td>".JText::_('DT_REGISTRATION_FEE').": </td><td>".numberFormat($amount,2)."</td></tr>";


		$adminmsg.="<tr><td>".JText::_('DT_NUMBER_MEMBERS').": </td><td>".$memtot."</td></tr>";

// DT_PAY_LATER

		if ($paymentMethod !== 'free'){

		   //$adminmsg.="<tr><td>Payment type: </td><td>".$paymentMethod."</td></tr>";

           if ($type == 'pay_later')

              $adminmsg.="<tr><td>".JText::_( 'DT_PAYMENT_TYPE').": </td><td>" . JText::_('DT_PAY_LATER') . " (" .$payLaterOption. ")</td></tr>";

           else

              $adminmsg.="<tr><td>".JText::_('DT_PAYMENT_TYPE').": </td><td>".$lang_var[$type]."</td></tr>";

		}

        else {

             $adminmsg.="<tr><td>".JText::_('DT_PAYMENT_TYPE').": </td><td>Free</td></tr>";

        }

		 $adminmsg.="<tr><td>".JText::_('DT_CONFIRMATION_NUMBER').": </td><td>".$confirmNum."</td></tr>";

		 if($discount_code_id != 0){

			$dt_code = new DiscountCode($discount_code_id);

			$adminmsg.="<tr><td>".JText::_('DT_DISCOUNT_CODE').": </td><td>".$dt_code->code."</td></tr>";

	    }

		if ($userType == 'G'){

			$database->setQuery($sql2);

			$rowUser2=$database->loadObjectList();

			foreach ($_SESSION['register']['groupUser'] as $key => $value){

				$adminmsg .= "<tr><td colspan='2'>&nbsp;</td></tr>";

				$adminmsg.="<br /><tr><td colspan='2'>".JText::_('DT_MEMBER')." {$key}</td></tr>";

				foreach ($value as $key2 => $value2){

					if ($key2=='firstname' || $key2=='lastname'){

						$memberNames .= ' ' . stripslashes($value2);

						if ($key2=='lastname'){$memberNames .= '<br />';}

					}

					if($value2==""){

						continue;

					}

					if ($key2=='firstname'){$adminmsg .= "<tr><td>" . JText::_('DT_FIRSTNAME') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='lastname'){$adminmsg .= "<tr><td>" . JText::_('DT_LASTNAME') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='organization'){$adminmsg .= "<tr><td>" . JText::_('DT_ORGANIZATION') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='address'){$adminmsg .= "<tr><td>" . JText::_('DT_ADDRESS') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='city'){$adminmsg .= "<tr><td>" . JText::_('DT_CITY') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='state'){$adminmsg .= "<tr><td>" . JText::_('DT_STATE') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='zip'){$adminmsg .= "<tr><td>" . JText::_('DT_ZIPCODE') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='country'){$adminmsg .= "<tr><td>" . $key2 . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='email'){$adminmsg .= "<tr><td>" . JText::_('DT_EMAIL') . ": </td><td>". $value2 ."</td></tr>";}

					else if ($key2=='phone'){$adminmsg .= "<tr><td>" . JText::_('DT_PHONE') . ": </td><td>". $value2 ."</td></tr>";}

					else {

						//$adminmsg .= "<tr><td>" . $key2 . ": </td><td>". $value2 ."</td></tr>";

					}

				}

					if ($arrCustomFields){

						foreach ($arrCustomFields as $key3 => $value3){

							if($value[$key3]==""){

								continue;

							}

							if ($value[$key3]){$adminmsg .= "<tr><td>".$value3.':</td><td>'.$value[$key3].'</td></tr>';

							$groupCustomFields .= $value3.': '.$value[$key3].'<br />';}

						}

				}

			}

		}

		$adminmsg.="</table>";

	//Get the admin email now and the thank you message

	$sql = "SELECT a.summary,a.dtstart, a.dtend,b.email,b.thksmsg,b.thksmsg_set FROM #__jevents_vevdetail a,#__dtregister_group_event b WHERE a.evdet_id=b.eventId  AND  a.evdet_id=$eventId";

	$database->setQuery($sql);

	$rowAdminEmail = $database->loadObject();

    $sql1 = "SELECT *  FROM #__dtregister_config WHERE config_key='thanksemail'";

    $database->setQuery($sql1);

	$defaultthksmsg = $database->loadObject();
	
	 $defaultthksmsg = $defaultthksmsg->config_value ;

	if($rowAdminEmail->email){

		$adminemail=$rowAdminEmail->email;

		$thksmsg=stripslashes($rowAdminEmail->thksmsg);

		$thksmsg_set=$rowAdminEmail->thksmsg_set;

		$eventBegin=$rowAdminEmail->dtstart;

		$eventEnd=$rowAdminEmail->dtend;

		$eventTitle=stripslashes($rowAdminEmail->summary);

	} else {

		$adminemail=$DT_mailfrom;

	}

	// If custom email message is selected... use it!

		$constants = array('[FIRSTNAME]','[NAME]','[ORGANIZATION]','[EVENT_NAME]','[EVENT_DATE]','[CONTACT_DETAILS]','[GROUP_NAMES]','[GROUP_NUMBER]','[AMOUNT]','[PAYMENT_TYPE]','[CONTACT_CUSTOM_FIELDS]','[GROUP_CUSTOM_FIELDS]','[CONFIRM_NUM]');

		//if ($type=='pay_later'){$type='Pay Later';}

		$replace = array($fname,$fname.' '.$lname, $org, $eventTitle, get_date($eventBegin,$eventEnd), $contactDetails, $memberNames, $memtot, numberFormat($amount,2), $lang_var[$type], $contactCustomFields, $groupCustomFields,$confirmNum);

	if ($thksmsg_set == 1){

		$thanksemail = str_replace($constants, $replace, $thksmsg);

	} else {

        $thanksemail = str_replace($constants, $replace, $defaultthksmsg);

	}

    $sql = "SELECT config_value , id FROM #__dtregister_config WHERE config_key='subthanksemail'";

    $database->setQuery($sql);

	$subthanksemail = $database->loadResult();

	$subthanksemail = str_replace('[EVENT_NAME]',$eventTitle,$subthanksemail);

	// send out the messages if not a PayPal payment -- these get sent out on return from paypal

	if ($type != 'Paypal' && $paymentVerified == 1){

	  if (isset($uid)){

		registration_email_frontend($uid);

		//JUtility::sendMail($mosConfig_mailfrom,$mosConfig_fromname,$adminemail,stripslashes($subadmin),stripslashes(nl2br($adminmsg)),1);

//		JUtility::sendMail($mosConfig_mailfrom, $mosConfig_fromname,$email,stripslashes($subthanksemail),stripslashes(nl2br($thanksemail)),1);

    }

	}else{

	   $later = array('Mail','Phone','At_door');

	   if(in_array($type,$later)){

	   		registration_email_frontend($uid);

	   }

	}

	if ($type == 'Paypal'){

		# $mail->send( $mosConfig_mailfrom, $mosConfig_fromname,$adminemail,stripslashes($subadmin),stripslashes(nl2br($adminmsg)),1);

		return $uid;

	}

  unset($_SESSION['register']);

  return $uid;

}

// the process part of fullEventPage

// gets form info and sends it in an email to the email listed on the admin side

function saveWaiting($option,$eventId)

{

	global $Itemid,$DT_fromname,$DT_mailfrom;

	$database = &JFactory::getDBO();

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$conf = &JFactory::getConfig();
     if($DT_mailfrom == ""){
     $DT_mailfrom = $conf->_registry['config']['data']->mailfrom;
  }
  if($DT_fromname==""){
     $DT_fromname =$conf->_registry['config']['data']->fromname;
  }
//	$mosConfig_mailfrom = $conf->_registry['config']['data']->mailfrom;

	//$mosConfig_fromname =$conf->_registry['config']['data']->fromname;

	$fname=$database->getEscaped($_POST['fname']);

	$lname=$database->getEscaped($_POST['lname']);

	$numberRegistrants=$database->getEscaped($_POST['number_registrants']);

	$address=$database->getEscaped($_POST['address']);

	$city=$database->getEscaped($_POST['city']);

	$state=$database->getEscaped($_POST['state']);

	$zip=$database->getEscaped($_POST['zip']);

	$country=$database->getEscaped($_POST['country']);

	$email=$database->getEscaped($_POST['email']);

	$phone=$database->getEscaped($_POST['phone']);

	$sql="Insert Into #__dtregister_waiting(event_id,fname,lname,phone,email,address,state,country,zip,number_registrants,created)

	Values($eventId,".$database->Quote($fname).",".$database->Quote($lname).",".$database->Quote($phone).",".$database->Quote($email).",".$database->Quote($address).",".$database->Quote($state).",".$database->Quote($country).",".$database->Quote($zip).",$numberRegistrants,now());

		";

	$database->setQuery($sql);

	$database->query();

	$sql="SELECT summary,dtstart,dtend FROM #__jevents_vevdetail WHERE evdet_id=$eventId";

	$database->setQuery($sql);

	$row = $database->loadObject();

	$eventName=$row->summary;

	$startDate=$row->dtstart;

	$endDate=$row->dtend;

	$start_date =JFactory::getDate($row->dtstart)->toFormat('%b %d, %Y');

	$end_date  = JFactory::getDate($row->dtend)->toFormat('%b %d, %Y');

	$event_date = get_date($row->dtstart,$row->dtend,null,true);

	if($start_date != $end_date ){

		$event_date .= " - ".get_date($row->dtend,null,true);

	}

	//Send email to administrator

	$sql="Select email From #__dtregister_group_event Where eventId=$eventId";

	$database->setQuery($sql, 0, 1);

	$adminEmail=$database->loadResult();

	//if(!$adminEmail)

	$adminMsg="<table>

	<tr><td colspan='2'>You have a new Waiting List addition for the ".addslashes($eventName).".</td>

	<tr><td colspan='2'>The new add-on details are:</td>

	<tr><td>Event Name:</td><td>".addslashes($eventName)."</td></tr>

	<tr><td>Event Date:</td><td>$event_date</td></tr>

	<tr><td>First name:</td><td>".addslashes($fname)."</td></tr>

	<tr><td>Last name:</td><td>".addslashes($lname)."</td></tr>

	<tr><td>Number registrants:</td><td>$numberRegistrants</td></tr>

	<tr><td>Address:</td><td>".addslashes($address)."</td></tr>

	<tr><td>City:</td><td>".addslashes($city)."</td></tr>

	<tr><td>State:</td><td>".addslashes($state)."</td></tr>

	<tr><td>Zip:</td><td>$zip</td></tr>

	<tr><td>Country:</td><td>$country</td></tr>

	<tr><td>Email:</td><td>".addslashes($email)."</td></tr>

	<tr><td>Phone:</td><td>".addslashes($phone)."</td></tr>

	</table>

		";
    $email=$DT_mailfrom;
	$adminSubject=" New Waiting List addition";

    $pos = strrpos($adminEmail, ";");

		if ($pos === false) { 

			$adminemails = array($adminEmail);

		}else{

			$adminemails  = explode(";",$adminEmail);

		}
       
		foreach($adminemails as $value){  
           
			JUTility::sendMail($DT_mailfrom, $DT_fromname,$value,$adminSubject,($adminMsg),1);

		}

	//JUtility::sendMail($email,$mosConfig_fromname,$adminEmail,$adminSubject,$adminMsg,1);

	//Get event name and display the header

	?>

<div class="componentheading"><?php echo JText::_('DT_REGISTRATION');?>: <?php echo $eventName?></div>

<table width="100%">

	<tr>

		<td>&nbsp;&nbsp;</td>

	</tr>

	<tr>

		<td width="100%"><?php echo $waiting_msg?></td>

	</tr>

	<tr>

		<td>&nbsp;&nbsp;</td>

	</tr>

	<tr>
         
		<td><a href="<?php echo  JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid,$xhtml_url);?>"><?php echo JText::_('DT_RETURN_TO_EVENTS');?></a>

		</td>

	</tr>

</table>

	<?php

}

// called from an ajax request via billingInfo()

// If Duplicate Registration Prevention is on it checks for eventId, email and payment verification and returns 1 if found

function duplicationCheck($option)

{

	$database = &JFactory::getDBO();
    ob_clean();
	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	$sql="Select config_value From #__dtregister_config where config_key = 'prevent_duplication'";
    $database->setQuery($sql);
	$prevent_duplication=$database->loadResult();
	$global_prevent_duplication = $prevent_duplication ;
	$eventId=$_GET['eventId'];
    $evt = new Event($eventId);
    
    $evt->over_ride_global(true);
	 $my = &JFactory::getUser();
	if(!$my->id && $cb_integrated > 0 && $usercreation==1){
	    
	   	$email=$_GET['email'];
        $username = $_GET['username'];
		$sql="SELECT COUNT(*) FROM #__users WHERE username='$username' ";

		$database->setQuery($sql);

		$total=$database->loadResult();
		
		if($total){

			echo "3";
            die ;
		}
		
		$sql="SELECT COUNT(*) FROM #__users WHERE email='$email' ";

		$database->setQuery($sql);

		$total=$database->loadResult();
		
		if($total){

			echo "4";
            die ;
		}
		
	}
	if($prevent_duplication==1){
	  $prevent_duplication = $global_prevent_duplication;
	}else{
	  $prevent_duplication = 0 ;
	}
	
	if(!$prevent_duplication){

		echo "2";

	}else{

		$email=$_GET['email'];

		$sql="SELECT COUNT(*) FROM #__dtregister_user WHERE eventId='$eventId' AND userEmail='$email' and cancel <> 1";

		$database->setQuery($sql);

		$total=$database->loadResult();

		if($total){

			echo "1";

		}else{

			echo "0";

		}

	}

}

// security image check

function securityCheck($option)

{

	$database = &JFactory::getDBO();

	$code=JRequest::getVar('security_code','');

	$userIp=$_SERVER['REMOTE_ADDR'];

	//Check database

	$sql="Select count(*) From #__dtregister_captcha where user_ip='$userIp' and code='$code'";

	$database->setQuery($sql);

	$total=$database->loadResult();

	$_SESSION['register']['secCheck'] = $total;
   
	if($total){

		echo "1";

	}else{

		echo "0";

	}

}

function paypal_notify($payMethod){

 ob_start();

	global $database,$Itemid,$my,$ptc;

	$database = &JFactory::getDBO();

   require_once(JPATH_SITE.'/components/com_dtregister/paypal.class.php');  // include the class file

	 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	  $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			 $sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);

			 $_SESSION = $data;
			 $lang =& JFactory::getLanguage();
             
$lang->load('com_dtregister');
   
	 $p = new paypal_class; // initiate an instance of the class

	// $paypalmode = 'test';

	 $p->paypal_url = ($paypalmode=='test')?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url

       	//$database->query($query);

		//@ob_clean();
  
	  if($p->validate_ipn() && ($_REQUEST['payment_status']=='Completed' || $_REQUEST['payment_status']=='Pending' || $_REQUEST['payment_status']=='Processed')){
         
	  	 $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			 $sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);

			 $_SESSION = $data;
             $_SESSION['register']['billingInfo']['transaction_id'] = $_REQUEST['txn_id'] ;
			  
             //if(1){
			 if($row[0]->user_id == 0){           
			  $userId = saveInfo('Paypal',1);
              
		       $sql = "update #__dtregister_session set user_id='".$userId."' where id=".$paypal_session_id;

	         $database->setQuery($sql);

              $database->query();

		      registration_email_frontend($userId);

          }

	 }
	 global $p ;
	 $p->mark('ENDIPN');
	 echo "<pre>";
	 print_r($_REQUEST);
	 print_r($p->getBuffer());

	 $msg = ob_get_clean();
	// JUTility::sendMail($DT_mailfrom, $DT_fromname,'test@dthdevelopment.com',"test",$msg,1); //test@dthdevelopment.com
	 header('HTTP/1.1 200 OK');
die;

	   $query = "INSERT INTO `#_dtregister_ipn_debug` (`user_id` ,`fields` ,`data`)VALUES ('".$userId."', '".mysql_real_escape_string($p->ipn_response)."','".mysql_real_escape_string(serialize($_REQUEST))."')" ;

  $database->setQuery($query);

	$database->query();

die;

}

// display custom fields

function idealRaboCancel($option){
   
     $mosConfig_live_site = JURI::root( false );
     $msg .= '<strong>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</strong>';
     
	echo $msg.'<p><a href="'.JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a></p></form>';
   
}
function idealRaboError($option){
    
	 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

   	 $eventId = 	$_SESSION['register']['eventId'];

     $evt = new Event($_GET['eventId']);

     $evt->over_ride_global();

   global $mainframe , $Itemid;

   echo JText::_( 'DT_ERROR_PAYMENT_IDEAL' );

   echo "</form>";
	
}
function idealRaboSuccess($option){
   
 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

   	 $eventId = 	$_SESSION['register']['eventId'];

     $evt = new Event($_GET['eventId']);

     $evt->over_ride_global();

    global $mainframe , $Itemid;

   $mosConfig_live_site = JURI::base( true );

      saveInfo('ideal',1);

}

function displayPaymentForm($payMethod){
   
	global $Itemid,$ptc;

	$user = &JFactory::getUser();

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::root( false );

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

    $event_Id = $_SESSION['register']['eventId'];

	$evt = new Event($event_Id);
    
    $evt->over_ride_global();
	 if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
	   $paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
	}else{
	  $paid_amount = $_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee']-$_SESSION['register']['discount_code_amount'];
	}
	
	 $amount = str_replace(",",".",numberFormat($paid_amount));
	if($currency_code==""){$currency_code='USD';}
    
		switch ($payMethod){
            
			 case 'idealRabo':
             
			 $urlCancel = "{$mosConfig_live_site}index.php?option=com_dtregister&task=payment&type=idealRaboCancel&userId=$userId&Itemid=$Itemid&eventId=$event_Id";
			 $urlSuccess = "{$mosConfig_live_site}index.php?option=com_dtregister&task=payment&type=idealRaboSuccess&userId=$userId&Itemid=$Itemid&eventId=$event_Id";
			 $urlError = "{$mosConfig_live_site}index.php?option=com_dtregister&task=payment&type=idealRaboError&userId=$userId&Itemid=$Itemid&eventId=$event_Id";
			 
			 include(JPATH_SITE."/components/com_dtregister/lib/ideallite.php");
			 
			 $oIdeal = new IdealLite();
			 $oIdeal->sCurrency = $currency_code ;
			 $oIdeal->setUrlCancel($urlCancel);
	         $oIdeal->setUrlSuccess($urlSuccess);
	         $oIdeal->setUrlError($urlError);
			 
			 $oIdeal->setAmount($amount);
	         $oIdeal->setOrderId(1);
	        $oIdeal->setOrderDescription($evt->summary);
			
			echo $oIdeal->createForm();
			 
			 //include("components/com_dtregister/view/payment/idealRabo.php");
              
			break ;
			
            case 'ideal':
              $task = "payment" ;
			  $type = "processIdeal";
			  include(JPATH_SITE."/components/com_dtregister/view/payment/ideal.php");

			  echo "</form>";

			break ;

			case "paypal": {

				// go to saveInfo()

			   global $Itemid;

			   require_once(JPATH_SITE.'/components/com_dtregister/paypal.class.php');  // include the class file

			   $eventId = $_SESSION['register']['eventId'];

				 $custom ="amountCharged=$amount|";

				 $custom .="memtot=".$_SESSION['register']['memtot']."|";

				 $custom .="regtype=".ltrim($_SESSION['register']['reg_type'],'reg_')."|";

				 $custom .="eventId=$eventId|";

				//Connect data
                
				$billing_info = $_SESSION['register']['billingInfo'];

				if($currency_code==""){$currency_code='USD';}

				//Get the event title

				$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

				$database->setQuery($sql);

				$itemName=$database->loadResult();

			 	// $userId = saveInfo('Paypal',0);

				//$sql = "INSERT INTO #__dtregister_paypal_session (`session_id` ,`data`)VALUES ( '".session_id()."','".mysql_real_escape_string(serialize($_SESSION),$database->_resource)."')" ;

				$sql = "INSERT INTO #__dtregister_session (`session_id` ,`data`, `user_id`)VALUES ( ".$database->Quote(session_id()).",".$database->Quote(serialize($_SESSION)).",0)" ;

				$database->setQuery($sql);

				$database->query();

				$rowid=$database->insertid();

				$custom .="userId=$userId|";

				$custom .="session=$rowid";

				$p = new paypal_class; // initiate an instance of the class

				$p->paypal_url = ($paypalmode=='test')?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url

				$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

			      $p->add_field('business', "$paypalid");

						$p->add_field('return', "{$mosConfig_live_site}index.php?option=com_dtregister&task=payment&type=paypal_payreturn&userId=$userId&amount=$amount&Itemid=$Itemid&eventId=$eventId");

			      $p->add_field('cancel_return', "{$mosConfig_live_site}index.php?option=com_dtregister&task=payment&type=paypal_payfailure&Itemid=$Itemid&eventId=$eventId&userId=$userId");

			      $p->add_field('notify_url', "{$mosConfig_live_site}components/com_dtregister/paypal_ipn.php?amount=$amount");

				  if($paypalmode=='test'){

				  		$p->add_field('test_ipn', 1);

				  }

			    $p->add_field('item_name', $itemName);

				  $p->add_field('first_name', $billing_info['firstname']);

				  $p->add_field('last_name', $billing_info['lastname']);

				  $p->add_field('address1', $billing_info['address']);

				  $p->add_field('city', $billing_info['city']);

  				$p->add_field('state', $billing_info['state']);

				  $p->add_field('zip', $billing_info['zip']);

			    $p->add_field('amount', "$amount");

				  $p->add_field('custom', "$custom");

				  $p->add_field('email', $billing_info['email']);

				  $punct = preg_quote("().-+", '/');

				  $billing_info['phone'] = preg_replace("/[$punct]/", '', $billing_info['phone']);

				  $p->add_field('night_phone_a', substr($billing_info['phone'],0,3));

				  $p->add_field('night_phone_b', substr($billing_info['phone'],3,3));

				  $p->add_field('night_phone_c', substr($billing_info['phone'],-4));

				  $phone 		= $_SESSION['register']['billingInfo']['email'];

				  //add currency to the form

				  $p->add_field('currency_code',$currency_code);
                 
			    $p->submit_paypal_post(); // submit the fields to paypal
                 }
				break;

			case "authorizenet":{
 
				$eventId = $_SESSION['register']['eventId'];

				//Load credit card data

				if($cb_integrated ==1 )

				{

					$userId=$user->id;

					if ($userId)

					{

						//Get the information from cb

						$sql="Select * From #__comprofiler where user_id=$userId";

						$database->setQuery($sql);
						$rowProfile =  false ;
                        if($cb_integrated==1)
						$rowProfile = $database->loadObject();

						if($rowProfile)

						{

							//Decode some string

              global $ptc;

							$ptc->ToDecode=$rowProfile->cb_creditcardnumber;

							$ptc->Decode();

							if($ptc->Decoded!=-1)

								$rowProfile->cb_creditcardnumber=$ptc->Decoded;

							$ptc->ToDecode=$rowProfile->cb_expdate;

							$ptc->Decode();

							if($ptc->Decoded!=-1)

								$rowProfile->cb_expdate=$ptc->Decoded;

						}

					}

				}

				?>

				<table>

				<?php

                $billinginfo = $_SESSION['register']['billingInfo'] ;

				?>

				<?php

                if($_SESSION['register']['memtot']==1){

				?>

		        <tr><td colspan="2" ><strong><?php echo JText::_( 'DT_PAYMENT_INFORMATION' );?></strong></td></tr>

                <tr><td colspan="2" >&nbsp;</td></tr>

                <tr>

                	<td><?php echo JText::_( 'DT_SAME_BILLING_INFO' );?></td>

                	<td><input type="checkbox" name="same" id="same" value="1" /></td>

                </tr>

		        <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CARD_HOLDER_FIRSTNAME' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_firstname" type="text" name="billing_firstname" value="<?php echo isset($billinginfo['billing_firstname'])?$billinginfo['billing_firstname']:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CARD_HOLDER_LASTNAME' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_lastname" type="text" name="billing_lastname" value="<?php echo isset($billinginfo['billing_lastname'])?$billinginfo['billing_lastname']:'' ?>" /> </td>

                 </tr>

                   <tr>

                	<td width="31%"  ><?php echo JText::_( 'DT_BILLING_ADDRESS' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_address" type="text" name="billing_address" value="<?php echo isset($billinginfo['billing_address'])?$billinginfo['billing_address']:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CITY' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" ><input id="billing_city" type="text" name="billing_city" value="<?php echo isset($billinginfo['billing_city'])?$billinginfo['billing_city']:'' ?>" />  </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_STATE' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input  id="billing_state"type="text" name="billing_state" value="<?php echo isset($billinginfo['billing_state'])?$billinginfo['billing_state']:'' ?>" /> </td>

                 </tr>

                  <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_ZIPCODE' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_zipcode" type="text" name="billing_zipcode" value="<?php echo isset($billinginfo['billing_zipcode'])?$billinginfo['billing_zipcode']:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_EMAIL' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_email" type="text" name="billing_email" value="<?php echo isset($billinginfo['billing_email'])?$billinginfo['billing_email']:'' ?>" /> </td>

                 </tr>

                <script src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>

				<script language="javascript" type="text/javascript" >
                    //<![CDATA[
					//jQuery.noConflict();
                    	var billing_firstname = "<?php echo $billinginfo['firstname'] ; ?>";

					var billing_lastname = "<?php echo $billinginfo['lastname']; ?>";

					var billing_address = "<?php echo $billinginfo['address']; ?>";

					var billing_city = "<?php echo $billinginfo['city']; ?>";

					var billing_state = "<?php echo $billinginfo['state']; ?>";

					var billing_zipcode = "<?php echo $billinginfo['zip']; ?>";

					var billing_email = "<?php echo $billinginfo['email']; ?>";
					DTjQuery(function(){

						DTjQuery("#same").click(function(){

							if(this.checked){

								DTjQuery("#billing_firstname").val(billing_firstname);

								DTjQuery("#billing_lastname").val(billing_lastname);

								DTjQuery("#billing_address").val(billing_address);

								DTjQuery("#billing_city").val(billing_city);

								DTjQuery("#billing_state").val(billing_state);

								DTjQuery("#billing_zipcode").val(billing_zipcode);

								DTjQuery("#billing_email").val(billing_email);

							}else{

								DTjQuery("#billing_firstname").val('');

								DTjQuery("#billing_lastname").val('');

								DTjQuery("#billing_address").val('');

								DTjQuery("#billing_city").val('');

								DTjQuery("#billing_state").val('');

								DTjQuery("#billing_zipcode").val('');

								DTjQuery("#billing_email").val('');

							}

						});

					});

                      //]]>
                   </script>

                <?php 

				}else{
				
				?>
                
                    <input id="billing_firstname" type="hidden" name="billing_firstname" value="<?php echo isset($billinginfo['firstname'])?$billinginfo['firstname']:'' ?>" /> 

                    <input id="billing_lastname" type="hidden" name="billing_lastname" value="<?php echo isset($billinginfo['lastname'])?$billinginfo['lastname']:'' ?>" /> 

                   <input id="billing_address" type="hidden" name="billing_address" value="<?php echo isset($billinginfo['address'])?$billinginfo['address']:'' ?>" /> 

                   <input id="billing_city" type="hidden" name="billing_city" value="<?php echo isset($billinginfo['city'])?$billinginfo['city']:'' ?>" /> 

<input  id="billing_state"type="hidden" name="billing_state" value="<?php echo isset($billinginfo['state'])?$billinginfo['state']:'' ?>" /> <input id="billing_zipcode" type="hidden" name="billing_zipcode" value="<?php echo isset($billinginfo['zip'])?$billinginfo['zip']:'' ?>" />  <input id="billing_email" type="hidden" name="billing_email" value="<?php echo isset($billinginfo['email'])?$billinginfo['email']:'' ?>" /> </td>

                 </tr>
                
                <?php
				
				}

				?>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CARD_TYPE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

				  <td width="69%" align="left" ><?php

				  $cardtypearr = explode(",",$cardtype);

				  $cardType=$rowProfile->cb_cardtype;

                  if(isset($billinginfo['cardtype'])){

				  		$cardType = $billinginfo['cardtype'] ; 

				  }

				  if(isset($billinginfo['x_card_num'])){

				  	 $rowProfile->cb_creditcardnumber = $billinginfo['x_card_num'] ;

				  }

				  if(isset($billinginfo['x_card_code'])){

				  	 $x_card_code = $billinginfo['x_card_code'] ;

				  }else{

				  	$x_card_code = "";

				  }

				   if(isset($billinginfo['x_exp_date'])){

				  	 $rowProfile->cb_expdate = $billinginfo['x_exp_date'] ;

				  }

                 $size = count($cardtypearr);
				if($size==1){
				   echo $cardtypearr[0];
				   
				    ?>
                    <input type="radio" style="display:none"  name="cardtype" value="<?php echo  $cardtypearr[0];?>"  <?php  echo "checked"; ?> />
                  <?php
				   
				}
				 
				   if($size>1)

				for($i=0;$i<count($cardtypearr);$i++)

				{?>

		        <input type="radio" name="cardtype" value="<?php echo  $cardtypearr[$i];?>"  <?php if($cardtypearr[$i]==$cardType) echo "checked"; ?> /><?php echo  $cardtypearr[$i];?><br />

				<?php } ?>

		       </td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CARD_NUMBER' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		         <td width="69%" align="left" ><input type="text" name="x_card_num" onKeyUp="chknumber(this)" class="inputbox" value="<?php echo $rowProfile->cb_creditcardnumber?>" />

		              <br />

		            <?php echo JText::_( 'CARD_NUMBER_EXPLANATION' );?></td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CARD_EXPIRY_DATE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		          <td width="69%" align="left" ><input type="text" name="x_exp_date" value="<?php echo $rowProfile->cb_expdate?>" class="inputbox" />

		            &nbsp;&nbsp;(mm/yy)</td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CVV_CODE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		         <td width="69%" align="left" ><input type="text" name="x_card_code" size="10" onKeyUp="chknumber(this)" class="inputbox" value="<?php echo $x_card_code ;?>" />

		            <?php echo JText::_( 'CVV_CODE_EXPLANATION' );?></td>

		        </tr>

				<?php

				$my = &JFactory::getUser();

				if ($cb_integrated == 1 && $save_payment_info == 1 && $my->id){?>

	    		<tr>

			    	<td><?php echo JText::_( 'DT_SAVE_INFO' ); ?>: </td>

			    	<td> <input type="checkbox" name="ckb_save_info" value="1" /> <?php echo JText::_( 'DT_SAVE_INFO_FUTURE' );?> </td>

			    </tr>

				<?php } ?>

		        <tr>

		          <td>

                  <input type="button" onclick="this.form.type.value='back';this.form.submit();" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

                  <input type="button" name="send" value="<?php echo JText::_('DT_NEXT_BUTTON'); ?>" class="button" onclick="sendPayment();" /></td>

		          <td align="left" >&nbsp;<input type="hidden" name="authPayment" value="1" /><input type="hidden" name="task" value="payment" /><input type="hidden" name="type" value="processAuthorizenet" /></td>

		        </tr>

		        </table>

		        </form>

				<script language="javascript" type="text/javascript">
                    //<![CDATA[
					function chknumber(txtname){

						var num = txtname.value

					    if(isNaN(num)){

							alert("<?php echo JText::_( 'DT_NUMBERS_ONLY' ); ?>");

							txtname.value = "";

					    	txtname.focus();

						}

					}

					function sendPayment(){

						var form=document.frmcart;

						<?php

						if($_SESSION['register']['memtot']==1){

						?>

						if(form.billing_firstname.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_FIRSTNAME_ERROR' ); ?>");

							form.billing_firstname.focus();

							return ;

						}

						if(form.billing_address.value==""){

							alert ("<?php echo JText::_( 'DT_ADDRESS_ERROR' ); ?>");

							form.billing_address.focus();

							return ;

						}

						if(form.billing_city.value==""){

							alert ("<?php echo JText::_( 'DT_CITY_ERROR' ); ?>");

							form.billing_city.focus();

							return ;

						}

						if(form.billing_state.value==""){

							alert ("<?php echo JText::_( 'DT_STATE_ERROR' ); ?>");

							form.billing_state.focus();

							return ;

						}

						if(form.billing_zipcode.value==""){

							alert ("<?php echo JText::_( 'DT_ZIP_ERROR' ); ?>");

							form.billing_zipcode.focus();

							return ;

						}

						if(form.billing_email.value==""){

							alert ("<?php echo JText::_( 'DT_EMAIL_ERROR' ); ?>");

							form.billing_email.focus();

							return ;

						}

						<?php

						}

						?>

						var checked=false;

                        if(typeof form.cardtype.length =='undefined'){
						   checked =true ;
						   cardType = form.cardtype.value;
						}else{

							for(var i=0;i<form.cardtype.length;i++){
	
								if(form.cardtype[i].checked==true){
	
									cardType = form.cardtype[i].value;
	
									checked=true;
	
									break;
	
								}
	
							}
						}

						if(!checked){

							alert ("<?php echo JText::_( 'DT_CC_CARD_TYPE' ); ?>");

							return;

						}

						if(form.x_card_num.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_NUMBER' ); ?>");

							form.x_card_num.focus();

							return ;

						}

						if(form.x_exp_date.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_EXPIRE_DATE' ); ?>");

							form.x_exp_date.focus();

							return ;

						}

						if(form.x_card_code.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_CODE' ); ?>");

							form.x_card_code.focus();

							return ;

						}

						confirmText = "<?php echo JText::_( 'DT_CONFIRM_CC_INFO' ); ?>\n\n";

						<?php

						//Get custom fields and store in CustomFields array

						$sql="SELECT f.id , f.name,f.label FROM #__dtregister_fields f, #__dtregister_field_event e WHERE  e.field_id=f.id and f.hidden=0 AND e.event_id=$eventId and (e.showed=1 or (e.showed =2 and f.showed=1))";

						$database->setQuery($sql);

						$rows=$database->loadObjectList();

						$arrCustomFields=array();

						for($i=0,$n=count($rows);$i<$n;$i++){

							$tmparray = array($rows[$i]->label => $rows[$i]->name);

							array_push_associative($arrCustomFields,$tmparray);

						}

						foreach ($_SESSION['register']['billingInfo'] as $key=>$value){

							if (array_search($key,$arrCustomFields)!= FALSE){$key = array_search($key,$arrCustomFields);}
							$value = trim( preg_replace( '/\s+/', ' ', $value ) );

						?>

						<?php } ?>

						confirmText = confirmText+"\n<?php echo JText::_( 'CARD_TYPE' ); ?>: \t "+cardType+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CARD_NUMBER' ); ?>: "+form.x_card_num.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CARD_EXPIRY_DATE' ); ?>: "+form.x_exp_date.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CVV_CODE' ); ?>:\t "+form.x_card_code.value+"\n";
                        confirmText = confirmText+"<?php echo JText::_( 'DT_AMOUNT' ); ?>:\t <?php echo $amount; ?>";
						var answer = confirm(confirmText);

						if (answer){
                            document.frmcart.send.disabled = true ;
							form.submit();

						}

					}

				</script>

				<?php
                 }
				break;

			case "echeck":{

				$database = &JFactory::getDBO();

				$eventId = $_SESSION['register']['eventId'];

				//Load bank data

				if($cb_integrated==1)

				{

					$userId=$user->id;

					if ($userId){

						//Get the information from cb

						$sql="Select * From #__comprofiler where user_id=$userId";

						$database->setQuery($sql);
                        $rowProfile =  false ;
                        if($cb_integrated==1)
						$rowProfile = $database->loadObject();

						if($rowProfile){

							//Decode the bank info

							global $ptc;

							$ptc->ToDecode=$rowProfile->cb_routingnumber;

							$ptc->Decode();

							if($ptc->Decoded!=-1){

								$rowProfile->cb_routingnumber=$ptc->Decoded;

							}

							$ptc->ToDecode=$rowProfile->cb_acctnumber;

							$ptc->Decode();

							if($ptc->Decoded!=-1){

								$rowProfile->cb_acctnumber=$ptc->Decoded;

							}

						}

					}

				}

				?>

				 <?php

                $billinginfo = $_SESSION['register']['billingInfo'] ;

				?>

				<table>

				<!--  <tr><td><?php echo JText::_( 'TOTAL_REGISTRATION_COST' );?>: <?php echo $currency_symbol; ?><?php echo numberFormat($_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee'],2)?></td></tr> -->

			 	<tr><td colspan="2" ><strong><?php echo JText::_( 'DT_BANK_INFORMATION' ) ?></strong><br /></td></tr>

								<?php

                if($_SESSION['register']['memtot']==1){

				?>

		        <tr><td colspan="2" ><strong><?php echo JText::_( 'DT_PAYMENT_INFORMATION' );?></strong></td></tr>

                <tr><td colspan="2" >&nbsp;</td></tr>

                <tr>

                	<td><?php echo JText::_( 'DT_SAME_BILLING_INFO' );?></td>

                	<td><input type="checkbox" name="same" id="same" value="1" /></td>

                </tr>

                   <tr>

                	<td width="31%"  ><?php echo JText::_( 'DT_BILLING_ADDRESS' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_address" type="text" name="billing_address" value="<?php echo isset($billinginfo['billing_address'])?$billinginfo['billing_address']:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CITY' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" ><input id="billing_city" type="text" name="billing_city" value="<?php echo isset($billinginfo['billing_city'])?$billinginfo['billing_city']:'' ?>" />  </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_STATE' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input  id="billing_state"type="text" name="billing_state" value="<?php echo isset($billinginfo['billing_state'])?$billinginfo['billing_state']:'' ?>" /> </td>

                 </tr>

                  <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_ZIPCODE' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_zipcode" type="text" name="billing_zipcode" value="<?php echo isset($billinginfo['billing_zipcode'])?$billinginfo['billing_zipcode']:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_EMAIL' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_email" type="text" name="billing_email" value="<?php echo isset($billinginfo['billing_email'])?$billinginfo['billing_email']:'' ?>" /> </td>

                 </tr>

                <script src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>

				<script language="javascript" type="text/javascript">
                     //<![CDATA[
					//jQuery.noConflict();
                        	var billing_address = "<?php echo $billinginfo['address']; ?>";

					var billing_city = "<?php echo $billinginfo['city']; ?>";

					var billing_state = "<?php echo $billinginfo['state']; ?>";

					var billing_zipcode = "<?php echo $billinginfo['zip']; ?>";

					var billing_email = "<?php echo $billinginfo['email']; ?>";
					DTjQuery(function(){

						DTjQuery("#same").click(function(){

							if(this.checked){

								DTjQuery("#billing_address").val(billing_address);

								DTjQuery("#billing_city").val(billing_city);

								DTjQuery("#billing_state").val(billing_state);

								DTjQuery("#billing_zipcode").val(billing_zipcode);

								DTjQuery("#billing_email").val(billing_email);

							}else{

								DTjQuery("#billing_address").val('');

								DTjQuery("#billing_city").val('');

								DTjQuery("#billing_state").val('');

								DTjQuery("#billing_zipcode").val('');

								DTjQuery("#billing_email").val('');

							}

						});

					});

                     //]]>
                   </script>

                <?php 

				}

				if(isset($_REQUEST['x_bank_aba_code'])){

					$rowProfile->cb_routingnumber = $_REQUEST['x_bank_aba_code'] ;

				}

				if(isset($_REQUEST['x_bank_acct_num'])){

					$rowProfile->cb_acctnumber = $_REQUEST['x_bank_acct_num'] ;

				}

				if(isset($_REQUEST['x_bank_name'])){

					$rowProfile->cb_bankname = $_REQUEST['x_bank_name'] ;

				}

				if(isset($_REQUEST['x_bank_acct_name'])){

					$rowProfile->cb_accountholder = $_REQUEST['x_bank_acct_name'] ;

				}

				if(isset($_REQUEST['x_bank_acct_type'])){

					$x_bank_acct_type = $_REQUEST['x_bank_acct_type'] ;

				}else{

					$x_bank_acct_type = 'CHECKING' ; 

				}

				?>

			    <tr><td><?php echo JText::_( 'DT_BANK_ROUTING_NUMBER' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

					<td><input type="text" name="x_bank_aba_code" onKeyUp="chknumber(this)" class="inputbox"  size="20" maxlength="16" value="<?php echo $rowProfile->cb_routingnumber?>"/></td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_NUMBER' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><input type="text" name="x_bank_acct_num" onKeyUp="chknumber(this)" class="inputbox"  size="20" maxlength="16" value="<?php echo $rowProfile->cb_acctnumber?>"/></td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_TYPE' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><select name="x_bank_acct_type">

			        	<option value="CHECKING" <?php echo($x_bank_acct_type=='CHECKING')?'selected':''?>><?php echo JText::_( 'DT_BANK_CHECKING' ); ?></option>

						<option value="SAVINGS" <?php echo($x_bank_acct_type=='SAVINGS')?'selected':''?>><?php echo JText::_( 'DT_BANK_SAVINGS' ); ?></option>

						</select>

			        </td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_NAME' ); ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><input type="text" name="x_bank_name" class="inputbox" size="30" value="<?php echo $rowProfile->cb_bankname?>"/></td></tr>

			  	<tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_HOLDER' ); ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td><td><input type="text" name="x_bank_acct_name" class="inputbox" size="30" value="<?php echo $rowProfile->cb_accountholder?>"/></td></tr>

				<?php

				$my = &JFactory::getUser();

				if ($cb_integrated == 1 && $save_payment_info == 1 && $my->id){?>

	    		<tr>

	    			<td><?php echo JText::_( 'DT_SAVE_INFO' ); ?>: </td>

			    	<td> <input type="checkbox" name="ckb_save_info" value="1" /> <?php echo JText::_( 'DT_SAVE_INFO_FUTURE' );?> </td>

			    </tr>

				<?php } ?>

					<tr><td colspan="2" align="center">&nbsp;</td></tr>

					<tr><td colspan="2" align="center">

						<input type="hidden" name="task" value="payment" />

						<input type="hidden" name="type" value="processEcheck" />

						<input type="button" onclick="this.form.type.value='';this.form.submit();" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

						<input type="button" name="send" value="<?php echo JText::_( 'DT_SEND_BUTTON' ); ?>" class="button" onclick="sendPayment();" />

					</td></tr>

				</table>

				</form>

				<script language="javascript" type="text/javascript">
                   //<![CDATA[
					function chknumber(txtname){

						var num = txtname.value

					    if(isNaN(num)){

							alert("<?php echo JText::_( 'DT_NUMBERS_ONLY' ); ?>");

							txtname.value = "";

					    	txtname.focus();

						}

					}

					function sendPayment(){

						var frm=document.frmcart;

						var form=document.frmcart;

						<?php

						if($_SESSION['register']['memtot']==1){

						?>

						if(form.billing_address.value==""){

							alert ("<?php echo JText::_( 'DT_ADDRESS_ERROR' ); ?>");

							form.billing_address.focus();

							return ;

						}

						if(form.billing_city.value==""){

							alert ("<?php echo JText::_( 'DT_CITY_ERROR' ); ?>");

							form.billing_city.focus();

							return ;

						}

						if(form.billing_state.value==""){

							alert ("<?php echo JText::_( 'DT_STATE_ERROR' ); ?>");

							form.billing_state.focus();

							return ;

						}

						if(form.billing_zipcode.value==""){

							alert ("<?php echo JText::_( 'DT_ZIP_ERROR' ); ?>");

							form.billing_zipcode.focus();

							return ;

						}

						if(form.billing_email.value==""){

							alert ("<?php echo JText::_( 'DT_EMAIL_ERROR' ); ?>");

							form.billing_email.focus();

							return ;

						}

						<?php

						}

						?>

						if(frm.x_bank_aba_code.value==""){

								alert ("<?php echo JText::_( 'DT_BANK_ROUTING' ); ?>")

								frm.x_bank_aba_code.focus();

								return;

						}

						if(frm.x_bank_acct_num.value==""){

							alert ("<?php echo JText::_( 'DT_BANK_ACCOUNT' ); ?>")

							frm.x_bank_acct_num.focus();

							return;

						}

						if(frm.x_bank_name.value=='' || frm.x_bank_acct_name.value.charAt(0)==' '){

							  alert("<?php echo JText::_( 'DT_BANK_NAME' ); ?>");

							  frm.x_bank_name.focus();

							  return;

					  	}

						if(frm.x_bank_acct_name.value=='' || frm.x_bank_acct_name.value.charAt(0)==' '){

						  	alert("<?php echo JText::_( 'DT_BANK_USER' ); ?>");

						  	frm.x_bank_acct_name.focus();

							return;

						}

						confirmText = "<?php echo JText::_( 'DT_CONFIRM_BANK_ACCOUNT_INFO' ); ?>\n";

						<?php

						//Get custom fields and store in CustomFields array

						$sql="SELECT f.id , f.name,f.label FROM #__dtregister_fields f, #__dtregister_field_event e WHERE e.field_id=f.id and f.hidden=0 AND e.event_id=$eventId and (e.showed=1 or (e.showed =2 and f.showed=1))";

						$database->setQuery($sql);

						$rows=$database->loadObjectList();

						$arrCustomFields=array();

						for($i=0,$n=count($rows);$i<$n;$i++){

							$tmparray = array($rows[$i]->label => $rows[$i]->name);

							array_push_associative($arrCustomFields,$tmparray);

						}

						foreach ($_SESSION['register']['billingInfo'] as $key=>$value){

							if (array_search($key,$arrCustomFields)!= FALSE){$key = array_search($key,$arrCustomFields);}
							$value = trim( preg_replace( '/\s+/', ' ', $value ) );

						?>

							// confirmText = confirmText+"<?php echo $key . ": \t" . $value; ?>\n";

						<?php } ?>

						confirmText = confirmText+"\n<?php echo JText::_( 'DT_BANK_ROUTING_NUMBER' ); ?>:\t"+frm.x_bank_aba_code.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_NUMBER' ); ?>:\t"+frm.x_bank_acct_num.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_TYPE' ); ?>:\t\t"+frm.x_bank_acct_type.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_NAME' ); ?>:\t\t"+frm.x_bank_name.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_HOLDER' ); ?>:\t"+frm.x_bank_acct_name.value;

						var answer = confirm(confirmText);

						if (answer){

							frm.submit();

						}

					}
                 //]]>
				</script>

				<?php
                 }
				break;

			case "pay_later":{

				// save and give confirmation on registration

				if (is_numeric($_GET['pay_later_option'])){$_SESSION['register']['pay_later_option'] = $_GET['pay_later_option'];}

				echo $_SESSION['register']['pay_later_option'] . " displayPaymentForm " . $payMethod;
              }
				break;
			default :{
			    			 
				 require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['paymentMethod'].'.php');
				
			     $payment =  new $_SESSION['register']['paymentMethod']();
				 $payment->setBillinginfo($_SESSION['register']['billingInfo']);
				 $payment->setPaymentType('registeration');
				 $payment->beforepayment();
				  $data =  array(
				        'eventName'=>  $evt->summary ,
						'amount'=>$amount 
				 );
				 if($_SESSION['register']['paymentMethod']=='GoogleCheckout')
				echo "</form>";
				 
				 $payment->setData($data);
				 $options = array('message'=>JText::_( 'DT_'.strtoupper($_SESSION['register']['paymentMethod']).'_REDIRECT_MSG' ));
				 echo $payment->showform($options) ;
				 
			}
			break ;

		}

}

// Append associative array elements

function array_push_associative(&$arr) {

	$args = func_get_args();
    $ret = 0;
	foreach ($args as $arg) {

		if (is_array($arg)) {

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

				$arr[$key] = $value;

				$ret++;

			}

		}else{

			$arr[$arg] = "";

		}

	}

	return $ret;

}

/*************************************

 * Main Function list

 * these functions do all the work

 ************************************/

/* listEvents -

 * Displays a list of events that the user has the option to register for.

 * This the first thing displayed when DTRegister is viewed

*/
function listEvents($option){

	global $Itemid ,$now , $month_arr;

     include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$database = &JFactory::getDBO();
    
    $document	=& JFactory::getDocument();
   // $document->addScript( JURI::root(true).'/media/system/js/mootools.js');
    $document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.js');

	$document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.lightbox.js');
		
    ?>
        
    <?php
	$document->addStyleSheet(JURI::root(true).'/components/com_dtregister/assets/css/jquery.lightbox.css');

    if(isset($googlekey) && $googlekey !=""){
      
	  $document->addScript( "http://maps.google.com/maps?file=api".$amp."v=2.x".$amp."key=".$googlekey);

	}

    //$document->addScriptDeclaration("/*<![CDATA[*/ \n jQuery.noConflict(); \n /*]]>*/");

	?>

    <script type="text/javascript" >

    //<![CDATA[

	 var map = null;


    var geocoder = null;

	var address = null;
	
	var display_address = null;

    function initialize() {
     
      if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById("map_canvas"));

        map.setCenter(new GLatLng(37.4419, -122.1419), 13);

        geocoder = new GClientGeocoder();

		showAddress(address);

      }

    }

    function showAddress(address) {

      if (geocoder) {

        geocoder.getLatLng(

          address,

          function(point) {

            if (!point) {

              alert(address + " not found");

            } else {

              map.setCenter(point, 13);

              var marker = new GMarker(point);

              map.addOverlay(marker);

              marker.openInfoWindowHtml(display_address);

            }

          }

        );

      }

    }
	
	DTjQuery(function(){ 

	  window.status='test';

	  DTjQuery(".colorbox").colorbox({width:550, height:550});

	  DTjQuery().bind('cbox_complete', function(){

		  initialize();
         // setTimeout($.fn.colorbox.next, 1500);
         //setTimeout("initialize()", 1500);

       });

	})
    //]]>
	</script>

    <?php
     
	 $task = JRequest::getVar('task','');
	 
	include_once( JPATH_SITE.'/includes/pageNavigation.php' );

		$sort = JRequest::getVar('category',"");
 
		$search = JRequest::getVar('search');

		$database->getEscaped( trim( strtolower( $search ) ) );

		$sql = "SELECT categoryId, categoryName , parent_id FROM #__dtregister_categories  ORDER BY ordering ";

	  	$database->setQuery($sql);

	  	$rows1 = $database->loadObjectList();

	    $options=array();
        $children = array(); 
		
        foreach ($rows1 as $v )
		{
			$pt = $v->parent_id;
			$list = @$children[$pt] ? $children[$pt] : array();
			array_push( $list, $v );
			$children[$pt] = $list;
		}
		
	    $options=array();
		$options[] =  JHTML::_('select.option',"",JText::_( 'DT_CATEGORY_VIEW' ));
		$options[]=JHTML::_('select.option',"0","All");
		foreach($children[0] as $pcategory){
		   $options[]=JHTML::_('select.option',$pcategory->categoryId,$pcategory->categoryName);
		   if(isset($children[$pcategory->categoryId])){
		       foreach($children[$pcategory->categoryId] as $childcat){
			       $options[]=JHTML::_('select.option',$childcat->categoryId,"--".$childcat->categoryName);
			   }
		   }
		}
	  
	    $arrkeys=array();

	    $arrvalues=array();

	    $arrCategory = array();
        
	    for ($i=0,$n=count($rows1);$i<$n;$i++){

	    	$row1 = $rows1[$i];

	    	$catId = $row1->categoryId;

	    	$catName = $row1->categoryName;

	    	//$options[]=JHTML::_('select.option',$catId,$catName);
            
	    	$tmpArr=array($catId=>$catName);

	    	array_push_associative($arrCategory,$tmpArr);

	    }

        $arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

				break;

			} else {
	
				$currency_symbol = NULL;
	
			}

		}

	// Display the table headers

	?>

	<!-- START of Events List Display -->
   
	<form action="<?php echo  JRoute::_("index.php?option=".$option."&Itemid=".$Itemid, $xhtml_url ); ?>" method="post" name="sort">
   <table  class="message" width="100%">
    <tr>
    <th colspan="3" class="componentheading"><?php echo JText::_( 'DT_EVENT_REGISTRATION' );?></th></tr>

		<tr><td colspan="2"><?php echo JText::_( 'DT_EVENT_LIST_INSTRUCTIONS' );?></td></tr>

    <tr>
    
    <td align="left">
    <?php if($event_search_show==1){ ?>
    <b><?php echo JText::_( 'DT_SEARCH' ); ?>:</b> 
     
    <input type="text" name="search" value="<?php echo $search; ?>" class="inputbox" />
    <input type="submit" value="<?php echo JText::_( 'DT_SEARCH_GO' );?>" />
    <?php } ?>
    </td>
    <td>
    <?php if($month_filter_show){ /// month filter flag 
	  
	  $month_opts = array();
	  
	  $month_opts[] = JHTML::_('select.option',"",JText::_( 'DT_SELECT_MONTH' ));
	  
	  foreach($month_arr as $key => $val){
	    $month_opts[]=JHTML::_('select.option',$key,$val);
	  }
	  $month =  JRequest::getVar('month'); //,date('m',$now->toUnix(true))
	  $year =  JRequest::getVar('year'); // ,date('Y',$now->toUnix(true))
	  
	  $year =  JRequest::getVar('year'); // ,date('Y',$now->toUnix(true))
	  echo JHTML::_('select.genericlist', $month_opts,"month",'onchange="submit()"',"value","text",$month); 
      
    $year_opts = array();
	  
	  $year_opts[] = JHTML::_('select.option',"",JText::_( 'DT_SELECT_YEAR' ));
      for($i=2015 ; $i > 2007; $i-- ){
	    $year_opts[]=JHTML::_('select.option',$i,$i);
	  }
      
	  echo JHTML::_('select.genericlist', $year_opts,"year",'onchange="submit()"',"value","text",$year); 
	  
	  ?>
       
       </td>     
       
       <?php }else{
	     $month = "";
	   } ?> 
    	<td align="right">
         <?php if($event_filter_show==1){?>
        <?php echo JHTML::_('select.genericlist', $options,"category",'onchange="submit()"',"value","text",$sort); ?>
         <?php } ?>
      </td>
          
     </tr>
   </table>
	<table class="message" width="100%">

	<?php $j=2; if($price_column){$j++;}if($capacity_column){$j++;}if($registered_column){$j++;} ?>

		<tr><th class="coltitle" align="left" width="<?php echo $event_field_width; ?>"><?php echo JText::_( 'DT_EVENT' );?></th>
         <?php if($event_date_show){ ?>
		    <th class="coltitle" align="left" width="<?php echo $event_date_width; ?>"><?php echo JText::_( 'DT_DATE' );?></th>
        <?php } ?>
	<?php

		if($price_column)

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_PRICE' ). '</th>';

		if($capacity_column)

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_CAPACITY' ). '</th>';

		if($registered_column)

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_REGISTERED' ).'</th>';

	?>

	</tr>

	<?php
    $condition_cats= "";
	  if($task == "category"){
	    
		$cats = array();
		for($i=1;$i<=12;$i++){
		  
		   $cat_id = JRequest::getVar('list'.$i,'');
		   if( $cat_id > 0){
		      $cats[] = $cat_id ;
		   }
		   
		}
		
		if(count($cats)>0){
		   $condition_cats = " and  c.categoryId in( ".implode(",",$cats)." ) ";
		}
		 
	 }
	if ($sort){ 
	    
		$search_cats = array();
		$search_cats[] = $sort ;
	    foreach($children[$sort] as $chCat){
		   
		    $search_cats[]  = $chCat->categoryId ;
		}
	    $sqlSort = "and  c.categoryId in( ".implode(",",$search_cats)." )";
    }else{
	   $sqlSort='';
	}

	// query title, description, date

	$search = $database->getEscaped( trim( strtolower( $search ) ) );

	if ($search){$sqlSearch = "AND (b.event_describe LIKE '%{$search}%' OR a.summary LIKE '%{$search}%' OR c.categoryName LIKE '%{$search}%'  OR l.name LIKE '%{$search}%' OR a.dtstart LIKE '%{$search}%' OR a.dtend LIKE '%{$search}%') ";}

if(!$show_past_event){

   $sqlShowPastEvent = " a.dtend >= '". $now->toUnix(true) ."' AND  "; //(b.startdate <= now() || b.startdate is null ) and

}else{

    $sqlShowPastEvent = "";

}
$config =& JFactory::getConfig();

$tzoffest = $config->getValue('config.offset');
if($month !="" && $year !="" ){
   
   $start_date = new JDate($year."-".$month."-01");

$config =& JFactory::getConfig();

$start_date->setOffset($config->getValue('config.offset'));

   $end_month = $month + 1 ;
   if($end_month > 12){
      $end_month = "01";
	  $end_year = $year + 1;
   }else{
      $end_year = $year ;
   }
    $end_date = new JDate($end_year."-".$end_month."-01");

$end_date->setOffset($config->getValue('config.offset'));
   
   $sqlmonth = " and a.dtstart >= ".($start_date->toUnix())." and a.dtstart <  ".($end_date->toUnix())." " ;
   
}

if($month =="" && $year !="" ){
   
   $start_date = $year."-01-01";

   $end_year =  $year + 1 ;


   $end_date = $end_year."-01-01" ;

   $sqlmonth = " and a.dtstart >= ".strtotime($start_date)." and a.dtstart <  ".strtotime($end_date)." " ;
   
}

	// query to get all the the current events that users can register for
     
	   $ordering = " b.ordering ASC ";
	
	$sql_tpl = "SELECT DISTINCT(a.evdet_id), c.*,a.*,b.cut_off_date,b.event_describe,b.event_describe_set,b.category,b.registerAmountIndividual, waiting_list , article_id ,  detail_link_show , b.show_registrant ,  if(b.startdate > '". $now->toFormat('%Y-%m-%d') ."' and b.startdate is not null,'y','n') as future_event ,b.location_id , b.max_registrations

		FROM #__jevents_vevdetail as a 
		inner join #__dtregister_group_event as b on a.evdet_id = b.eventId 
		left join #__dtregister_categories as c on c.categoryId = b.category 
        left join #__dtregister_locations as l on l.id = b.location_id 
		WHERE   ". $sqlShowPastEvent  ."  a.state=1 and b.publish=1 ".$condition_cats. $sqlmonth . $sqlSort . $sqlSearch ." [categories] 

		GROUP BY a.evdet_id

		ORDER BY  c.ordering, $ordering ";

   $sql = str_replace("[categories]"," ",$sql_tpl);
	$database->setQuery($sql);
  
	$rows = $database->loadObjectList();
    echo $database->getErrorMsg();
	function push_events($evts=array()){
	   global $events ;
	   
	   foreach($evts as $evt){
	     // array_push($events,$evt);
		  $events[] = $evt;
	   }
	   
	}
	global $events;
	$events = array();
	$sql = str_replace("[categories]"," and c.categoryId IS NULL  ",$sql_tpl);
	$database->setQuery($sql);
					
	$rows = $database->loadObjectList();
					 
	push_events($rows);
	
   	foreach($children[0] as $pcategory){
	     
		 $rows = array();
		 $sql = str_replace("[categories]"," and b.category=".$pcategory->categoryId,$sql_tpl);
		 $database->setQuery($sql);
		 
		 $rows = $database->loadObjectList();
		 
		 push_events($rows);
		 $rows = array();
	     if(isset($children[$pcategory->categoryId])){
		       foreach($children[$pcategory->categoryId] as $childcat){
			       $sql = str_replace("[categories]"," and b.category=".$childcat->categoryId,$sql_tpl);
					 $database->setQuery($sql);
					
					 $rows = $database->loadObjectList();
					 push_events($rows);
			   }
		 }
		 
	}
    
   $rows = $events;
	// if there are events, display them with the details for it

	// display 20 rows per page

	if($rows){

		$total = count($rows);

		$limit = trim( JRequest::getVar('limit',$event_list_number) );

		if($limit==""){

			$limit = $event_list_number ;

		}

		$limitstart = trim( JRequest::getVar('limitstart', 0 ) );

		$pageNav = new mosPageNav( $total, $limitstart, $limit );
 
		//$database->setQuery( $sql, $pageNav->limitstart, $pageNav->limit );

		//$rows=$database->loadObjectList();

		//Get the number of registrants
    $rows = array_splice($rows,$pageNav->limitstart,$pageNav->limit);
		for ($i=0,$n=count($rows);$i<$n;$i++)

		{

			$row=$rows[$i];
            
			 if($row->noendtime == 1){
			   $row->dtend = null ;
			 }
			
			//Get the Capacity

					//Get the number registrations

			$sql="SELECT SUM(c.numberOfPerson)

				  FROM #__dtregister_user AS a

				  INNER JOIN #__dtregister_group AS b

				  ON a.userId=b.useid

				  INNER JOIN #__dtregister_group_amount AS c

				  ON b.groupId=c.groupId

				  WHERE a.eventId=$row->evdet_id and a.cancel <> 1 

				  GROUP BY a.eventId

				";

			$database->setQuery($sql);

			$rows[$i]->registered=$database->loadResult();

		}

	//End the number of registrants

	$link="index.php?option=$option&Itemid=$Itemid";

	$prevCat=NULL;

	$currCat=NULL;

	// Display an event on each row

	for($i=0,$n=count($rows);$i<$n;$i++){

		if($i % 2 == 0){$bgRow='eventListRow1';}else{$bgRow='eventListRow2';}

		$row=$rows[$i];

		if (!$row->registered) {

			$row->registered=0;

		}

		//echo "<br />".$row->registered." >= ".$row->max_registrations ;

		if(($row->cut_off=='y') && ($row->cut_off_date!='0000-00-00'))

			$task="cut_off_date";

		elseif(($row->registered >= $row->max_registrations )&&($row->max_registrations)&&($row->waiting_list=='0'))

			$task="full_event_page";

		elseif(($row->registered>=$row->max_registrations)&&($row->max_registrations)&&($row->waiting_list=='1'))

      		$task="full_event_page_msg";

      	else

      		$task="reg_event";

		  $reglink = "index.php?option=$option&Itemid=$Itemid&eventId=$row->evdet_id&task=$task";

		  //$reglink=sefRelToAbs($reglink);

		// display the category for this event

		$currCat = $row->category;

		if($currCat!=$prevCat || $currCat==""){

			if ($arrCategory[$row->category]){
                $subclass = ($row->parent_id>0)?'class="subcategory"':'';
				$parent->categoryName = "";
				if($row->parent_id > 0){
				    
					$parent = new mosDtCategory($database);
					
					$parent->load($row->parent_id);
					$parent->categoryName .=" >> ";
				}
				echo '<tr class="categoryRow"><td colspan="'.$j.'" '. $subclass .' >'.$parent->categoryName.$arrCategory[$row->category].'</td></tr>';

			}

		}
		unset($article);
		unset($article_ItemId);
		$evt =  new Event($row->evdet_id);
        $article = $evt->get_article();

		$article_ItemId = $evt->get_article_Item($article);
		$prevCat = $currCat;
         $dt_event = new Event($row->evdet_id);
		 $jevent_view_id = $dt_event->get_jeventdetail_id();
         $jevent_href = JRoute::_("index.php?option=com_jevents&task=icalrepeat.detail&evid=".$jevent_view_id."&Itemid=".getcomItemId('com_jevents'),$xhtml_url);
         $dt_event->over_ride_global();
		 
		 $currency_symbol  = currency_symbol($currency_code);
		 if($event_title_link == "jevent"){
		     
             $event_title_href = $jevent_href;

		// }if($event_title_link == "article"){
		     
           //  $event_title_href = JRoute::_('index.php?option=com_content&view=article&id='.$article->id.'&Itemid='.$article_ItemId,$xhtml_url) ;

		 }else{
		 
		    $event_title_href = register_href($row->evdet_id);
		 }
     
		?>

		<tr <?php echo 'class="'.$bgRow.'"'; ?>>

        <?php if(($row->dtend > time() || $row->noendtime==1 ) && $row->future_event=='n'  ){  ; ?> 

		  	<td align="left" class="eventlist"><a href="<?php echo $event_title_href;?>"><?php echo $row->summary;?></a>

		<?php }else {?>

		<td align="left" class="eventlist"><?php echo $row->summary;?>

          <?php }?>

         <?php

           if($row->location_id !="" && $showlocation==1){

		      $loc = new DTlocation($database);

			  $loc->load($row->location_id);

			  if($loc->name !=""){

		 ?>
         
           <?php 
		 
		   echo "<br />&nbsp;".JText::_( 'DT_LOCATION')  ; ?>:&nbsp;<a class="colorbox" href="<?php echo JRoute::_("index.php?option=com_dtregister&task=showlocation&location=".$row->location_id."&no_html=1",$xhtml_url,false) ?>"   ><?php echo stripslashes($loc->name);?></a>

         <?php

		    if($linktogoogle==1){

		 ?>

         <?php

			}

			}

		   }

		 ?>

        <?php

              $br = false ;

		  if(is_numeric($row->article_id) && $row->article_id > 0 && $row->detail_link_show == 1){

			$mosConfig_live_site = JURI::base( true );

			if($front_link_type==1){

				$title = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/view_details_62x14.png" class="event_button" alt="'.JText::_('DT_DETAILS').'" />';

				$class = 'class="'.detailslink.'"' ;

				$start_brace = '';

				$end_brace = '';

			}else{

				$start_brace = '[';

				$end_brace = ']';

				$title = JText::_( 'DT_VIEW_DETAILS');

				$class = 'class="'.detailslink.'"' ;

			}

            $br = true ;
          echo '<br />'.$start_brace.'<a '.$class.' href="'.JRoute::_('index.php?option=com_content&view=article&id='.$article->id.'&Itemid='.$article_ItemId,$xhtml_url).'">'.$title.'</a>'.$end_brace;

		  }

		  if($row->show_registrant == 1){

			if($front_link_type==1){

				$title = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/attendees_62x14.png" class="event_button" alt="'.JText::_('DT_ATTENDEE').'" />';

				$class = 'class="'.detailslink.'"' ;

				$start_brace = '';

				$end_brace = '';

			}else{

				$start_brace = '[';

				$end_brace = ']';

				$title = JText::_( 'DT_VIEW_REGISTRANTS');

				$class = 'class="'.detailslink.'"' ;

			}

			  if(!$br){

			     echo '<br />';

			  }

			   $br = true ;
                 
				echo $start_brace.'<a '.$class.' href="'.JRoute::_('index.php?option=com_dtregister&eventId='.$row->evdet_id.'&task=registrant_list&Itemid='.$Itemid,$xhtml_url).'">'.$title.'</a>'.$end_brace;

		  }

		  if ($show_registration_button == 1 && ($row->dtend > time() || $row->noendtime==1 ) ){

               if(!$br){

			     echo '<br />';

			  }

			   $br = true ;

		  	echo $start_brace.register_link_small($row->evdet_id,$class).$end_brace;

		  }

		?>

        </td>
         <?php if($event_date_show){ ?>
		<td align="left" class="eventlist">

			<?php echo get_date($row->dtstart ,$row->dtend) ;//mosFormatDate($row->publish_up, "%b %d, %Y", true);

			$start_date =JFactory::getDate($row->dtstart)->toFormat('%b %d, %Y');

			$end_date  = JFactory::getDate($row->dtend)->toFormat('%b %d, %Y');

			if($start_date != $end_date && $row->dtend != ""){ echo ' - ' . get_date($row->dtend);}

			 //echo " -> " . $row->category;

			?> </td>
        <?php } ?>
	<?php if($price_column){?>

				<td align="left" class="eventlist"><nobr>

				<?php
                    $indrate = $evt->get_individual_rate() ;
					if (isset($currency_symbol) && trim($currency_symbol) != ""){

						if($indrate > 0){  $price = $indrate ;

						   echo $currency_symbol . ' ' . numberFormat($price,2);
						   if($show_price_tax && $evt->tax_enable){
							   $indrate += ($indrate*$evt->tax_amount)/100;
							     echo " (".JText::_("DT_WITHOUT_TAX").")"."<br />".$currency_symbol . ' ' . numberFormat($indrate,2)." (".JText::_("DT_WITH_TAX").")";
						  }

						}else{

						   echo JText::_( 'DT_FREE' );

						}

					} else {

                        if($indrate > 0){

						  echo numberFormat($indrate,2) . ' ' . $currency_code;
						  
						  if($show_price_tax && $evt->tax_enable){
							   $indrate += ($indrate*$evt->tax_amount)/100;
							   echo " (".JText::_("DT_WITHOUT_TAX").")"."<br />".numberFormat($indrate,2) . ' ' . $currency_code." (".JText::_("DT_WITH_TAX").")";
						  }

						}else{

						  echo JText::_( 'DT_FREE' );

						}

					}

					?>

				</nobr></td>

			<?php }

			if($capacity_column){

			?>

				<td align="left" class="eventlist">

				<?php

				if($row->max_registrations>0){

					echo $row->max_registrations;

				} else {

					echo JText::_( 'DT_UNLIMITED' );

				}

				?>

				</td>

			<?php

			}

			?>

			<?php if($registered_column){?>

				<td align="left" class="eventlist">

				<?php echo $row->registered;?>

				</td>

			<?php } ?>

		</tr>

		<?php if($row->event_describe_set){ ?>

		<tr <?php echo 'class="'.$bgRow.'"'; ?>><td colspan="<?php echo $j; ?>"><?php echo stripslashes($row->event_describe); ?></td></tr>

	<?php }
           $dt_event->resume_global();
		}// END LOOP -> for($i=0,$n=count($rows);$i<$n;$i++)?>

	</table>

	</form>

	<br /><br />

	<?php echo $pageNav->writePagesLinks($link);

	}else if (!$rows && $search){

		echo "<tr><td colspan='2'>".JText::_( 'DT_NO_SEARCH_RESULTS' )."</td></tr></table></form>";

	} else {

		// no events to list

		echo "<tr><td colspan='2'>".JText::_( 'DT_NO_EVENTS' )."</td></tr></table></form>";

	} // END -> if($rows)

}// END -> function listEvents

// No longer accepting registrations

function cutOffDate($option)

{

	global $Itemid;

	$database = &JFactory::getDBO();

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

/*	$eventId=mosGetParam($_REQUEST,'eventId',0);

	//Get eventName

	$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	$eventName=$database->loadResult();

*/

?>

	<table>

		<tr>

			<td>

				<?php echo $cut_off_date_message; ?>

			</td>

		</tr>

		<tr>

			<td>
               
				<a href="<?php echo  JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url); ?>"><?php echo JText::_( 'DT_RETURN_TO_EVENTS' ); ?></a>

			</td>

		</tr>

	</table>

<?php

}

function fullEventPage($option)

{

	global $Itemid , $mainframe;
    $user = &JFactory::getUser();
    $userId=$user->id;
	
	$database = &JFactory::getDBO();
     $mainframe = &JFactory::getApplication();
	$mosConfig_live_site = JURI::base( true );

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$eventId=JRequest::getVar('eventId',0);

    $dt_evt = new Event($eventId);
	if( $dt_evt->waiting_list==1){
	   $url = "index.php?option=com_dtregister&Itemid=".$Itemid;
	   $mainframe->redirect($url);
	}
	//Get event name

	$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	$eventName=$database->loadResult();

	$full_message=sprintf($full_message,$eventName);
	
	if($cb_integrated){

		if ($userId) {

			//Get the information from cb

			$sql="Select * From #__comprofiler where user_id=$userId";

			$database->setQuery($sql);
            if($cb_integrated==1)
			$rowProfile = $database->loadObject();

			$sql="Select email From #__users Where id=$userId";

			$database->setQuery($sql);

			$email=$database->loadResult();

      $both_fields = array ('city', 'state', 'address', 'zipcode', 'phone', 'company');
            
			$dt_user =  new DT_User();
            
			foreach($both_fields as $key=>$value){

				if(!isset($rowProfile->{'cb_'.$value})){

				  $rowProfile->{'cb_'.$value} = $rowProfile->{$value};

				}elseif(!isset($rowProfile->{$value})){

				  $rowProfile->{$value} = $rowProfile->{'cb_'.$value};

				}elseif(isset($rowProfile->{$value}) && isset($rowProfile->{'cb_'.$value})){

					if($rowProfile->{$value}=='' && $rowProfile->{'cb_'.$value}!=''){

						$rowProfile->{'cb_'.$value} = $rowProfile->{$value};

					}

					if($rowProfile->{'cb_'.$value}=='' && $rowProfile->{$value} !=''){

						$rowProfile->{'cb_'.$value} = $rowProfile->{'cb_'.$value};

					}

				}

			}
			$dt_user->loadJomsocial($rowProfile);

		}

	}

$fields_readyonly = "";
$dropdown_disable = "" ;
$my = &JFactory::getUser();
if($cb_integrated > 0 && $cbviewonly==1 && $my->id){
    $fields_readyonly = ' readonly="readonly" ';
	$dropdown_disable = " disabled ";
}

?>

<script type="text/javascript" language="javascript" src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/jx_dataCheck.js"></script>

<script type="text/javascript" language="javascript" src="components/com_dtregister/"></script>

<form method="POST" action="index.php?option=com_dtregister" name="frmcart" id="frmcart">

	<input type="hidden" name="option" value="<?php echo $option?>" />

	<input type="hidden" name="task" value="event_register" />

	<input type="hidden" name="type" value="save_waiting" />

	<input type="hidden" name="eventId" value="<?php echo $eventId?>" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<table class="authorizenetformtable">

		<tr>

			<td colspan="2">

				<?php echo $full_message;?>

			</td>

		</tr>

		<tr>

			<td colspan="2">&nbsp;</td>

		</tr>

		<tr >

			<td colspan="2" align="left" ><strong><?php echo JText::_( 'USER_INFORMATION' );?></strong></td>

		</tr>

			<tr><td colspan="2">( <span class="required">*</span> = <?php echo JText::_( 'DT_REQUIRED_FIELD' );?> )</td></tr>

			<tr>

			<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_FIRSTNAME' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

			<td width="69%" align="left" ><input <?php echo (isset($rowProfile->firstname) &&$rowProfile->firstname!="")?$fields_readyonly:''; ?> type="text" name="fname" value="<?php echo (isset($rowProfile->firstname))?stripslashes($rowProfile->firstname):''; ?>" class="inputbox" /></td>

			</tr>

			<tr>

			<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_LASTNAME' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

			<td width="69%" align="left" ><input <?php echo (isset($rowProfile->lastname)&& $rowProfile->lastname!="")?$fields_readyonly:''; ?> type="text" name="lname" value="<?php echo (isset($rowProfile->lastname))?stripslashes($rowProfile->lastname):''; ?>" class="inputbox" /></td>

			 </tr>

			<tr>

			<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_REGISTRANTS' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

			<td width="69%" align="left" ><input type="text" name="number_registrants" value="" class="inputbox" /></td>

			 </tr>

		<?php

		if($p_s_organization){?>

			<tr>

			<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_ORGANIZATION' );?>:

			<?php if($p_r_organization){ ?>

				<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

			<?php } ?>

			</td>

			<td width="69%" align="left" ><input <?php echo (isset($rowProfile->cb_company) && $rowProfile->cb_company!="")?$fields_readyonly:''; ?> type="text" name="organization" value="<?php echo (isset($rowProfile->cb_company))?stripslashes($rowProfile->cb_company):''; ?>" class="inputbox" /></td>

			</tr>

		<?php }

	if($p_s_address){?>

		<tr>

		<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS' );?>:

		<?php if($p_r_address) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>

		</td>

		<td width="69%" align="left" ><input <?php echo (isset($rowProfile->cb_address) && $rowProfile->cb_address!="")?$fields_readyonly:''; ?> type="text" name="address" value="<?php echo (isset($rowProfile->cb_address))?stripslashes($rowProfile->cb_address):''; ?>" class="inputbox" /></td>

		</tr>

	<?php

	}

	if($p_s_city){?>

		<tr>

		<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_CITY' );?>:

		<?php if($p_r_city) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>

		</td>

		<td width="69%" align="left" ><input <?php echo (isset($rowProfile->cb_city) && $rowProfile->cb_city!="")?$fields_readyonly:''; ?> type="text" name="city" value="<?php echo (isset($rowProfile->cb_city))?stripslashes($rowProfile->cb_city):''; ?>" class="inputbox" /></td>

		</tr>

	<?php

	}

	if($p_s_state){ ?>

		<tr>

		<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_STATE' );?>:

		<?php if($p_r_state){ ?> <span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

		</td>

		<td width="69%" align="left" >

        <input type="text" <?php echo (isset($rowProfile->cb_state) && $rowProfile->cb_state!="")?$fields_readyonly:''; ?> name="state" value="<?php echo (isset($rowProfile->cb_state))?stripslashes($rowProfile->cb_state):''; ?>" class="inputbox" />

        </td>

		</tr>

	<?php }

	if($p_s_zip){ ?>

		<tr>

		<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_ZIPCODE' );?>:

		<?php if($p_r_zip){ ?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

		</td>

		<td width="69%" align="left" ><input type="text" <?php echo (isset($rowProfile->cb_zipcode) && $rowProfile->cb_zipcode!="")?$fields_readyonly:''; ?>  name="zip" value="<?php echo (isset($rowProfile->cb_zipcode))?stripslashes($rowProfile->cb_zipcode):''; ?>" class="inputbox" /></td>

		</tr>

	<?php

	}

	if($p_s_country){ require_once(JPATH_SITE.'/components/com_dtregister/country.htm'); }

	?>

	<tr>

	<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_EMAIL' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

	<td width="69%" align="left" ><input <?php echo (isset($email) && $email!="")?$fields_readyonly:''; ?> type="text" name="email" value="<?php echo (isset($email))?stripslashes($email):''; ?>" class="inputbox" /></td>

	</tr>

	<tr>

	<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_CONFIRM_EMAIL' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

	<td width="69%" align="left" ><input <?php echo (isset($email) && $email!="")?$fields_readyonly:''; ?> type="text" name="cemail" value="<?php echo (isset($email))?stripslashes($email):''; ?>" class="inputbox" /></td>

	</tr>

	<?php if($p_s_phone){ ?>

			<tr>

			<td width="31%" class="fieldlabel"><?php echo JText::_( 'DT_PHONE' );?>:&nbsp;

			<?php if($p_r_phone) { ?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

			</td>

			<td width="69%" align="left" ><input <?php echo (isset($rowProfile->cb_phone) && $rowProfile->cb_phone!="")?$fields_readyonly:''; ?> type="text" name="phone" value="<?php echo (isset($rowProfile->cb_phone))?stripslashes($rowProfile->cb_phone):''; ?>" class="inputbox" />

			</td>

			</tr>

	<?php } ?>

			<?php

    		if($security_image_check)

    		{

    			global $mosConfig_live_site;

    		?>

				<tr>

					<td class="fieldlabel">

						<?php echo JText::_( 'DT_ENTER_SECURITY_CODE' ); ?>:

					</td>

					<td>

						<input type="text" name="security_code" size="15" />

						<img src="<?php echo JURI::root(true);?>/components/com_dtregister/CaptchaSecurityImages.php?width=100<?php echo $amp; ?>height=40<?php echo $amp; ?>characters=5" align="middle" alt="" />

					</td>

				</tr>

    		<?php

    		}

    	?>

			<tr>

				<td colspan="2">

					<input type="button" name="btnCancel" value=" Cancel  " class="button" onclick="window.history.go(-1);" />
                    
                    <input type="button" name="btnSubmit" value=" Submit  " class="button" onclick="checkData()"/>

				</td>

			</tr>

	</table>

</form>
<?php
if($p_s_country){
?>
 <script type="text/javascript">
    //<![CDATA[
	if(typeof(document.frmcart.country) != 'undefined')
	document.frmcart.country.value = "<?php echo isset($rowProfile->cb_country)?$rowProfile->cb_country:''; ?>";
	//]]>
  </script>
<?php
} 
?>
<script type="text/javascript">
//<![CDATA[

	function checkData(){

		if(document.frmcart.fname.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_FNAME' ); ?>");

			document.frmcart.ftname.focus();

			return;

		}

		if(document.frmcart.lname.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_LNAME' ); ?>");

			document.frmcart.lname.focus();

			return;

		}

		if(!parseInt(document.frmcart.number_registrants.value))		{

			alert ("<?php echo JText::_( 'DT_REGISTRANTS_INTEGER' ); ?>");

			document.frmcart.number_registrants.focus();

			return;

		}

		if(document.frmcart.number_registrants.value<1)		{

			alert ("<?php echo JText::_( 'DT_REGISTRANTS_MORE_THAN_ZERO' ); ?>");

			document.frmcart.number_registrants.focus();

			return;

		}

		<?php if($p_s_organization && $p_r_organization){ ?>

			if(document.frmcart.organization.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ORGANIZATION' ); ?>");

				document.frmcart.organization.focus();

				return;

			}

		<?php }

		if($p_s_organization && $p_r_organization){	?>

			if(document.frmcart.organization.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ORGANIZATION' ); ?>");

				document.frmcart.organization.focus();

				return;

			}

		<?php }

		if($p_s_address && $p_r_address){?>

			if(document.frmcart.address.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS' ); ?>");

				document.frmcart.address.focus();

				return;

			}

		<?php }

		if($p_s_city && $p_r_city){ ?>

			if(document.frmcart.city.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_CITY' ); ?>");

	    	document.frmcart.city.focus();

			return;

			}

		<?php }

		if($p_s_state && $p_r_state){ ?>

			if(document.frmcart.state.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_STATE' ); ?>");

			document.frmcart.state.focus();

			return;

			}

		<?php }

		if($p_s_zip && $p_r_zip){ ?>

			if(document.frmcart.zip.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ZIP' ); ?>")

			document.frmcart.zip.focus();

			return false;

			}

		<?php } ?>

		if(document.frmcart.email.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

			document.frmcart.email.focus();

			return;

		}

		if (document.frmcart.cemail.value==""){

	    	alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

	    	document.frmcart.cemail.focus();

		    return;

		}

		if(document.frmcart.email.value!=document.frmcart.cemail.value)	{

			alert("<?php echo JText::_( 'DT_EMAIL_MATCH' ); ?>");

			document.frmcart.cemail.focus();

			return;

		}

		if(document.frmcart.email.value!=""){

			var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

			var returnval=emailfilter.test(document.frmcart.email.value)

			if (returnval==false){

				alert("<?php echo JText::_( 'DT_INVALID_EMAIL' ); ?>");

				document.frmcart.email.select();

				document.frmcart.email.focus();

				return ;

			}

		}

		<?php if($p_s_phone & $p_r_phone){ ?>

				if(document.frmcart.phone.value==""){

					alert("<?php echo JText::_( 'DT_ENTER_PHONE' ); ?>");

					document.frmcart.phone.focus();

					return;

				}

		<?php }  ?>

		var security_image_check=<?php if($security_image_check){echo $security_image_check; } else { echo '0';}?>;

	  	if(security_image_check==1){

	  		var url='index2.php?option=com_dtregister&task=event_register&type=security_check&no_html=1&security_code=';

	  		var security_code=document.frmcart.security_code.value;

	  		url=url+security_code;

	  		if (security_code==""){

	  			alert("<?php echo JText::_( 'DT_ENTER_SECURITY_CODE' ); ?>");

	  			document.frmcart.security_code.focus();

	  			return;

	  		} else {

				jx.load(url,function(data){

					switch(parseInt(data)){

					case 0:

					alert("<?php echo JText::_( 'DT_MISMATCH_SECURITY_IMAGE' ); ?>");

					document.frmcart.security_code.focus();

					return;

					break;

					default:

					document.frmcart.submit();

					return;

					break;

					}

					}

				);

			}

	  	} else {

	  		// not checking security image - submit the form

	  		document.frmcart.submit();

	  	}

	}

//]]>
</script>

<?php

}

function fullEventPageMsg($option) {

?>

<form method="POST" action="<?php echo $mosConfig_live_site; ?>/index.php?option=com_dtregister" name="frmcart" id="frmcart">

	<table class="authorizenetformtable">

		<tr>

			<td colspan="2">

				<?php echo JText::_( 'DT_EVENT_FULL_MESSAGE' );?>

			</td>

		</tr>

  </table>

</form>

<?php

}

/* event_register -

 * Gets the event registration type and redirects accordingly

 */

function event_register($option, $eventId){

	global $Itemid, $mainframe;

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	//Get registration type

	$sql="Select registration_type from #__dtregister_group_event where eventId=$eventId";

	$database->setQuery($sql);

	$regtypeallowed=$database->loadResult();

	if($regtypeallowed==null){ $regtypeallowed="both"; }

	#echo $regtypeallowed;

	// redirect based on registration type

	switch($regtypeallowed){

		case 'individual':

			//$url=sefRelToAbs("index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_individual");

$url="index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_individual";

			$mainframe->redirect($url);

		break;

		case 'group':

			//$url=sefRelToAbs("index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_group_num");

$url="index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_group_num";

			$mainframe->redirect($url);

		break;

		case 'both':

		//	$url=sefRelToAbs("index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_options");

$url="index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_options";

			$mainframe->redirect($url);

		break;

	}

}

// Following function checks the event cutoff date in case the event was directly linked to and bypassed the cutoff check in the

// event list, module, plugin and JEvents hacked file.

function checkRegCutoff ($eventId) {

    global $now ;
	$database = &JFactory::getDBO();

	 $query= "SELECT if(cut_off_date = 0000-00-00,'n',if('". $now->toFormat('%Y-%m-%d')."'>cut_off_date,'y','n')) as cutoff FROM #__dtregister_group_event WHERE eventId=$eventId LIMIT 0,1";

	$database->setQuery($query);

	$cutoff = $database->loadResult();

	if ($cutoff == "y") return TRUE; else return FALSE;

}

// Here we enter the registration info for an individual register

// and also the billing info for a group registrant

 function billingInfo ($option, $eventId, $memtot ){

  	global $Itemid ,$now;

  	$user = &JFactory::getUser();

  	$database = &JFactory::getDBO();

  	$mosConfig_live_site = JURI::base( true );

	$eventId = $_SESSION['register']['eventId'];
    
	$dt_evt =  new Event($eventId);
  	$userId=$user->id;

  	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

  	$memtot = $_SESSION['register']['memtot'];

  	//echo $memtot;

 	if ($memtot<2){

		// GET all registration info about this event

	  	$query= "SELECT *,if('". $now->toFormat('%Y-%m-%d')."'>latefeedate,'y','n') as late , if('". $now->toFormat('%Y-%m-%d')."' < bird_discount_date and bird_discount_type<>0 and bird_discount_type <> 3,'y','n' ) as bird , bird_discount_type FROM #__dtregister_group_event WHERE eventId=".$eventId." AND memberTotal=".$memtot;

	  	$amountCharged = 0;

        $latefee =0;

         $discount_total=0;

		 $database->setQuery($query);

		 $res = $database->loadObjectList();

		  //for ($i=0,$n=count($res);$i<$n;$i++)

		//while($res=mysql_fetch_array($query))	\

		foreach($res as $r)

		{

			if($r->memberTotal >= $memtot){
                 
				 if($r->bird=='y'){

		             $r->registerAmountIndividual = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->registerAmountIndividual);

					   $_SESSION['register']['bird_discount'] = 1 ;

		         }elseif(isset($_SESSION['register']['bird_discount'])){
				    unset($_SESSION['register']['bird_discount']);
				 }

				$amountCharged = $r->registerAmountIndividual;

				if($r->late=='y'){

					//$latefee += $res['latefee'];

					$late_fee_rate = $r->latefee;

					$latefee  = $late_fee_rate ;

				}

			}

			 $discount_type = $r->discount_type;

			 $discount_amount = $r->discount_amount;

			 $late_fee_rate = $r->latefee;

			 $group_per_rate = $r->registerAmountIndividual;

			 $discount_per_rate = $r->discount_amount;

			$totalCharged = $amountCharged + $latefee;

			$_SESSION['register']['amountCharged']=	$amountCharged + $latefee;

		}

		if($userId>0){

			//Apply discount here

			$discount_total=0;

			if($discount_type==1 && $discount_type !=3){

				//Amount

				$discount_total = $discount_amount;

				$totalCharged=$totalCharged-$discount_amount;

			} elseif ($discount_type==2 && $discount_type !=3) {

				//Percent

				$discount_total = $totalCharged * ($discount_amount/100);

				$totalCharged=$totalCharged*(100-$discount_amount)/100;

			}

			//End of discount here

			$_SESSION['register']['discount']=$discount_total;

		}

              $_SESSION['register']['amountCharged']=$totalCharged;

  	}else { // memtot > 2

			 $query = "select *,if('". $now->toFormat('%Y-%m-%d')."'>latefeedate,'y','n') as late , if('". $now->toFormat('%Y-%m-%d')."' < bird_discount_date and bird_discount_type<>0 and bird_discount_type <> 3 ,'y','n' ) as bird , bird_discount_type from #__dtregister_group_event WHERE

	 			eventid=$eventId ORDER BY memberTotal ASC";

	 $database->setQuery($query);

	 $res = $database->loadObjectList();

	 $amountCharged = 0;

	 $latefee =0;

	 $userId=$user->id;

	  $discount=0;

	foreach($res as $r){

	 #$discount_per_rate = $r->discount_amount;

	 $discount=0;

	 	 // memberTotal is 'Number of members' on the admin side
        
         if($r->bird=='y'){

		    $r->regGroupPerRate = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->regGroupPerRate);

             $_SESSION['register']['bird_discount'] = 1 ;

		 }elseif(isset($_SESSION['register']['bird_discount'])){
				    unset($_SESSION['register']['bird_discount']);
				 }

		 if( (int)$memtot >= $r->memberTotal){

	 $discount_type = $r->discount_type;

	 $discount_amount = $r->discount_amount;

	 $late_fee_rate = $r->latefee;

	 $group_per_rate = $r->regGroupPerRate;

			$group_per_rate = $r->regGroupPerRate;

		 	if($userId>0){

		 		if($discount_type==1 && $discount_type !=3){

		 			$amountCharged = ($r->regGroupPerRate-$discount_amount)* $memtot;

		 			$discount = $discount_amount * $memtot;

		 		} elseif ($discount_type==2 && $discount_type !=3){

		 			$amountCharged = $r->regGroupPerRate*(100-$discount_amount) * $memtot/100;

                                        $discount = (($r->regGroupPerRate*$discount_amount)/100) * $memtot;

		 		} else {

		 			$amountCharged = $r->regGroupPerRate * $memtot;

		 		}

				$totalCharged =  $amountCharged;

				$discount = $discount ;

							    if($r->late=='y'){

									$latefee = $r->latefee*$memtot;

				$totalCharged = $latefee + $totalCharged;

								}

				 $_SESSION['register']['amountCharged']=$totalCharged;

				 $discount = $discount;

                 $_SESSION['register']['discount']=$discount;

		 	} else {

		 	 	$amountCharged = $r->regGroupPerRate * $memtot;

				$totalCharged =  $amountCharged;

			    if($r->late=='y'){

					$latefee = $r->latefee*$memtot;

					$totalCharged = $latefee + $totalCharged;

				}

 				$_SESSION['register']['amountCharged']=$totalCharged;

		 	}

				//break;

		 } else {

	 		break;

		 }

	 }

  	}

	//***************************

	//Get custom fields
     if(!isset($_SESSION['register']['reg_type']) || $_SESSION['register']['reg_type']==""){
	    
		$_SESSION['register']['reg_type'] = $_GET['type'] ;
	}
	//***************************

	//**************************

	//Get the user info from user profile

	if($cb_integrated){

		if ($userId) {

			//Get the information from cb

			$sql="Select * From #__comprofiler where user_id=$userId";

			$database->setQuery($sql);
           if($cb_integrated==1)
			$rowProfile = $database->loadObject();

			$sql="Select email From #__users Where id=$userId";

			$database->setQuery($sql);
           
			$email=$database->loadResult();

            $both_fields = array ('city', 'state', 'address', 'zipcode', 'phone', 'company');
            
			$dt_user =  new DT_User();
            
			foreach($both_fields as $key=>$value){

				if(!isset($rowProfile->{'cb_'.$value})){

				  $rowProfile->{'cb_'.$value} = $rowProfile->{$value};

				}elseif(!isset($rowProfile->{$value})){

				  $rowProfile->{$value} = $rowProfile->{'cb_'.$value};

				}elseif(isset($rowProfile->{$value}) && isset($rowProfile->{'cb_'.$value})){

					if($rowProfile->{$value}=='' && $rowProfile->{'cb_'.$value}!=''){

						$rowProfile->{'cb_'.$value} = $rowProfile->{$value};

					}

					if($rowProfile->{'cb_'.$value}=='' && $rowProfile->{$value} !=''){

						$rowProfile->{'cb_'.$value} = $rowProfile->{'cb_'.$value};

					}

				}

			}
			$dt_user->loadJomsocial($rowProfile);

		}

	}
  
	//*****************************

	//Get data entered by user

	$backFromConfirmPage=JRequest::getVar('back_from_confirm',0,'post');

	if(isset($_SESSION['register']['billingInfo'])){

		//Get the posted data and pass it into rowProfile object

		$title	= $_SESSION['register']['billingInfo']['title'];
		
		$firstname	= $_SESSION['register']['billingInfo']['firstname'];

		$lastname	= $_SESSION['register']['billingInfo']['lastname'];

		$organization=$_SESSION['register']['billingInfo']['organization'];

		$address	= $_SESSION['register']['billingInfo']['address'];
		
		$address2	= $_SESSION['register']['billingInfo']['address2'];

		$city 		= $_SESSION['register']['billingInfo']['city'];


		$state		= $_SESSION['register']['billingInfo']['state'];

		$zip		= $_SESSION['register']['billingInfo']['zip'];

		$country	= $_SESSION['register']['billingInfo']['country'];

		$email		= $_SESSION['register']['billingInfo']['email'];

		$phone		= $_SESSION['register']['billingInfo']['phone'];

		$rowProfile->title = $title ;
		
		$rowProfile->firstname=$firstname;

		$rowProfile->lastname=$lastname;

		$rowProfile->company=$organization;

		$rowProfile->cb_company=$organization;

		$rowProfile->address=$address;
		
		$rowProfile->address2=$address2;

        $rowProfile->cb_address=$address;
	
	   $rowProfile->cb_address2=$address2;

		$rowProfile->city=$city;

 		$rowProfile->cb_city=$city;

		$rowProfile->state=$state;

		$rowProfile->cb_state=$state;

		$rowProfile->zipcode=$zip;

		$rowProfile->cb_zipcode=$zip;

		$rowProfile->phone=$phone;

		$rowProfile->cb_phone=$phone;

		$rowProfile->country=$country;

		$rowProfile->cb_country=$country;

	}

	//End of get data entered by user

// get the event title

$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

$database->setQuery($sql);

$eventName=$database->loadResult();

// get the top message for this event - this is set on the admin side

$sql="Select topmsg , eventId from #__dtregister_group_event where eventId=$eventId";

$database->setQuery($sql, 0, 1);

$topmsg=$database->loadResult();

$sql="Select use_discountcode from #__dtregister_group_event where eventId=$eventId limit 0,1";

$database->setQuery($sql);

$use_discountcode=$database->loadResult();

$sql="Select terms_conditions_set from #__dtregister_group_event where eventId=$eventId";

$database->setQuery($sql, 0, 1);

$terms_conditions_set = $database->loadResult();

JHTML::_('behavior.calendar');
$fields_readyonly = "";
$dropdown_disable = "" ;
$my = &JFactory::getUser();
if($cb_integrated > 0 && $cbviewonly==1 && $my->id){
    $fields_readyonly = ' readonly="readonly" ';
	$dropdown_disable = " disabled ";
}
if($email=='0'){
  $email = "";
}
?>

	<table class="authorizenetformtable" width="100%">

	<tr><td><?php echo stripslashes($topmsg); ?></td></tr>

	<?php

    $arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

				break;

		} else {

			$currency_symbol = NULL;

		}

		}

		$discount = $_SESSION['register']['discount'];

    ?>

	<tr><td><br /><?php

		if ((int)$totalCharged > 0){

			echo JText::_( 'TOTAL_REGISTRATION_COST' ) . ': ';

    		if ($memtot > 1){echo $memtot . ' x ';}

 			if($memtot > 1 && ($discount>0 || $latefee>0)){echo "[";}

    		if($memtot > 1 || $discount>0 || $latefee>0){echo $currency_symbol. numberFormat($group_per_rate,2);}
            
			
			 if(isset($_SESSION['register']['bird_discount']) && $r->bird_discount_type != 3){

		       echo ' ('. JText::_( 'DT_BIRD_RATE' ).')' ;

		   }
			// echo $currency_symbol. numberFormat(($_SESSION['register']['amountCharged']+$discount+$latefee),2);

			if ($discount>0){?> - <?php echo $currency_symbol . numberFormat($discount,2) . ' ('.JText::_( 'DT_MEMBER_DISCOUNT' ).')' ; }

			if ($latefee>0){echo ' + ' . ' ' . $currency_symbol . numberFormat($late_fee_rate,2). ' ('.JText::_( 'DT_LATE_FEE' ).')' ; }

 			if($memtot > 1 && ($discount>0 || $latefee>0)){echo "]";}

			$customFee = 0 ;

			if ($_SESSION['register']['memtot'] > 1){

				$groupFee = 0;

				foreach($_SESSION['register']['groupUser'] as $key=>$value){

					$groupFee += $_SESSION['register']['groupUser'][$key]['customFee'];

				}

				$customFee += $groupFee;

				if($customFee > 0){

					echo " + ".$currency_symbol.numberFormat($customFee,2)." ".JText::_('DT_ADDITIONAL_FEES')." ";

				}

			}

		  if($memtot > 1 || $discount>0 || $latefee>0){echo " = ";}

      if (isset($currency_symbol)){

				echo $currency_symbol . ' ' . numberFormat($totalCharged+$customFee,2);

			} else {

				echo numberFormat($totalCharged+$customFee,2) . ' ' . $currency_code;

			}

			$field_used = "p";

		}else{

			$field_used = "f";

		}

           if(isset($_SESSION['register']['bird_discount']) && $r->bird_discount_type == 3){

		       echo ' ('. JText::_( 'DT_BIRD_RATE' ).')' ;

		   }

		?>

	</td></tr>

</table>

<table align='center' width='100%' border='0' cellpadding='2' cellspacing='2'>

	<tr><td colspan="3" align="justify"><?php echo stripslashes($cardtext);?></td></tr>

	<tr >

	<td colspan="3" align="left" ><strong>

	<?php

		if ($_SESSION['register']['reg_type'])

		if ($memtot > 1){ echo (($totalCharged+$customFee)>0)?JText::_( 'DT_BILLING_INFORMATION'):JText::_( 'DT_GROUP_CONTACT_INFORMATION' ); } else { echo JText::_( 'USER_INFORMATION' ); }

	?>

	</strong></td>

	</tr>

	<tr><td colspan="3">( <span class="required">*</span> = <?php echo JText::_( 'DT_REQUIRED_FIELD' );?> )</td></tr>

 <?php

	if($use_discountcode){

	?>

	<tr><td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_DISCOUNT_CODE'); ?>:</td>

      <td width="68%" align="left"><input type="text" name="discount_code" value="" class="inputbox" /></td><td width="2%">&nbsp;</td></tr>

    <?php }?>

   <?php

		if(${$field_used._s_title}){?>

			<tr>

			<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_TITLE' );?>:

			<?php if(${$field_used._r_title}){ ?>

				<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

			<?php } 
			    $titles = explode("|",$titleoptions);
			    $temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

			  foreach($titles as $title){
	
				$temp[] = JHTML::_('select.option', $title, $title);
	
			  }
	        
			  $titles = $temp;
			?>

			</td>

			<td width="68%" align="left" >
            <?php echo  JHTML::_('select.genericlist',$temp,'title', 'class="inputbox" size="1"', 'value', 'text',$rowProfile->title); ?>
            </td>
             <td width="2%">&nbsp;</td>
			</tr>

		<?php }
		?>
   
	<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_FIRSTNAME' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->firstname!="")?$fields_readyonly:''; ?> name="firstname" value="<?php echo stripslashes($rowProfile->firstname); ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
	</tr>

	<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_LASTNAME' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->lastname!="")?$fields_readyonly:''; ?> name="lastname" value="<?php echo stripslashes($rowProfile->lastname); ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
	 </tr>

		<?php

		if(${$field_used._s_organization}){?>

			<tr>

			<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_ORGANIZATION' );?>:

			<?php if(${$field_used._r_organization}){ ?>

				<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

			<?php } ?>

			</td>

			<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->cb_company!="")?$fields_readyonly:''; ?> name="organization" value="<?php echo stripslashes($rowProfile->cb_company); ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
			</tr>

		<?php }

	if(${$field_used._s_address}){?>

		<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS' );?>:

		<?php if(${$field_used._r_address}) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>

		</td>

		<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->cb_address!="")?$fields_readyonly:''; ?> name="address" value="<?php  if(stripslashes($rowProfile->cb_address)==""){echo $rowProfile->address;}else{echo stripslashes($rowProfile->cb_address);}; ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
		</tr>

	<?php

	}
	if(${$field_used._s_address2}){?>
	
		<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS2' );?>:

		<?php if(${$field_used._r_address2}) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>

		</td>

		<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->cb_address2!="")?$fields_readyonly:''; ?> name="address2" value="<?php  if(stripslashes($rowProfile->cb_address2)==""){echo $rowProfile->address2;}else{echo stripslashes($rowProfile->cb_address2);}; ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
		</tr>
  <?php
   }
	if(${$field_used._s_city}){?>

		<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_CITY' );?>:

		<?php if(${$field_used._r_city}) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>

		</td>

		<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->cb_city!="")?$fields_readyonly:''; ?> name="city" value="<?php echo stripslashes($rowProfile->cb_city); ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
		</tr>

	<?php

	}

	if(${$field_used._s_state}){ ?>

		<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_STATE' );?>:

		<?php if(${$field_used._r_state}){ ?> <span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

		</td>

		<td width="68%" align="left" >

        <input type="text" name="state" <?php echo ($rowProfile->cb_state!="")?$fields_readyonly:''; ?> value="<?php echo stripslashes($rowProfile->cb_state); ?>" class="inputbox" />

        </td>
<td width="2%">&nbsp;</td>
		</tr>

	<?php }

	if(${$field_used._s_zip}){ ?>

		<tr>

		<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_ZIPCODE' );?>:

		<?php if(${$field_used._r_zip}){ ?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

		</td>

		<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->cb_zipcode!="")?$fields_readyonly:''; ?> name="zip" value="<?php echo stripslashes($rowProfile->cb_zipcode); ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
		</tr>

	<?php

	}

	if(${$field_used._s_country}){ require_once(JPATH_SITE.'/components/com_dtregister/country.htm'); }

	?>

	<tr>

	<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_EMAIL' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

	<td width="68%" align="left" ><input type="text" <?php echo ($email!="")?$fields_readyonly:''; ?> name="email" value="<?php echo $email; ?>" class="inputbox" /></td>
<td width="2%">&nbsp;</td>
	</tr>

	<tr>

	<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_CONFIRM_EMAIL' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

	<td width="68%" align="left" ><input type="text" <?php echo ($email!="")?$fields_readyonly:''; ?> name="cemail" value="<?php echo $email; ?>" class="inputbox" /></td>
<td width="2%" >&nbsp;</td>
	</tr>

	<?php if(${$field_used._s_phone}){ ?>

			<tr>

			<td width="30%" class="fieldlabel"><?php echo JText::_( 'DT_PHONE' );?>:&nbsp;

			<?php if(${$field_used._r_phone}) { ?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

			</td>

			<td width="68%" align="left" ><input type="text" <?php echo ($rowProfile->cb_phone!="")?$fields_readyonly:''; ?> name="phone" value="<?php echo $rowProfile->cb_phone?>" class="inputbox" />

			</td>
<td width="2%" >&nbsp;</td>
			</tr>

	<?php }
     
	 if($_SESSION['register']['reg_type']=='reg_individual'){
		 $field_type = "I";
	 }else{
		  $field_type = "B";
	 }
	 if(!isset($_SESSION['register']['billingInfo'])){
	    $data =  array();
	 }else{
	    $data =  $_SESSION['register']['billingInfo'] ;
	 }
	 
	$field_html =  $dt_evt->field_html($field_type,(object)$data,false,'frmcart',false);
  	
  	if($field_html!="")

  	{

  	?>

      <tr><td colspan="3"><hr /></td></tr>

  		<tr><td colspan="3"><strong><?php echo JText::_( 'DT_ADDITIONAL_INFORMATION' );?></strong></td></tr>

  	<?php

  		echo $field_html ;

  	}

  	?>
    <?php
    if( !$userId && $usercreation) {
	?>
    <tr>

			<td class="fieldlabel"><?php echo JText::_( 'DT_USERNAME' ); ?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

			<td>

				<input type="text" name="username"  class="inputbox" />

			</td>
          <td width="2%" ><?php echo JHTML::tooltip(JText::_('DT_USERNAME_TIP'), '', 'tooltip.png', '', ''); ?></td>
		</tr>
      <tr>

			<td class="fieldlabel"><?php echo JText::_( 'DT_PASSWORD' ); ?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

			<td>

				<input type="password" name="password"  class="inputbox" />

			</td>
          <td width="2%" ><?php echo JHTML::tooltip(JText::_('DT_PASSWORD_TIP'), '', 'tooltip.png', '', '')?></td>
		</tr>
          <tr>

			<td class="fieldlabel"><?php echo JText::_( 'DT_CONFIRM_PASSWORD' ); ?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

			<td>

				<input type="password" name="confirm_password"  class="inputbox" />

			</td>
          <td width="2%" ><?php echo JHTML::tooltip(JText::_('DT_CONFIRM_PASSWORD_TIP'), '', 'tooltip.png', '', '')?></td>
		</tr>
    <?php
      }
	?>
  	<?php

    if($security_image_check)

    {

    ?>

		<tr>

			<td class="fieldlabel"><?php echo JText::_( 'DT_ENTER_SECURITY_CODE' ); ?>:</td>

			<td>

				<input type="text" name="security_code" size="15" />

				<img src="<?php echo  JURI::root(true);?>/components/com_dtregister/CaptchaSecurityImages.php?width=100<?php echo $amp; ?>height=40<?php echo $amp; ?>characters=5" alt="" align="middle" />

			</td>
          <td width="2%" >&nbsp;</td>
		</tr>

    <?php

    }

    if($terms_conditions)

    {

    ?>

		<tr>

			<td class="fieldlabel"><?php echo JText::_( 'DT_CHECK_TERMS_CONDITIONS' ); ?></td>

			<td>

				<input type="checkbox" id="terms_conditions0" name="terms_conditions" value="terms" /><label for="terms_conditions0"></label>

                <?php

                    if(defined('JVERSION'))

                       $sitelink=JURI::base();

                    else

                       $sitelink=$mosConfig_live_site;

                ?>

				<a href="<?php echo $sitelink . 'components/com_dtregister/terms.php?id=' . $_SESSION['register']['eventId']; ?>" id="terms_conditions"  class="lbOn"><?php echo htmlspecialchars  (JText::_( 'DT_TERMS_CONDITIONS_READ' )); ?></a>

                <span id="term_msg" style="display:none;">

			</span>

			</td>
         <td width="2%" >&nbsp;</td>
		</tr>

    <?php

    }

    ?>

	<tr>

		  <td colspan="3" align="center">&nbsp;</td>

    </tr>

		<tr><td colspan="3" align="center">

		<input type="hidden" name="task" value="event_register" />

		<input type="hidden" name="type" value="reg_info_check" />

    <input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

		<input type="hidden" name="eventId" value="<?php echo $_SESSION['register']['eventId']; ?>" />

		<input type="hidden" name="amountCharged" value="<?php echo $_SESSION['register']['amountCharged']=$totalCharged; ?>" />

<?php

$sql="Select registration_type from #__dtregister_group_event where eventId=$eventId";

$database->setQuery($sql, 0, 1);

$registration_type=$database->loadResult();

if($_SESSION['register']['reg_type'] =='reg_group'){

?>

		<input type="button" name="billingInfo"  value="<?php echo JText::_( 'DT_BACK' ); ?>" class="button" onclick="window.location='<?php echo  JRoute::_('index.php?option=com_dtregister&eventId='.$eventId.'&Itemid='.$Itemid.'&task=event_register&type=get_group_users&back=1&from=1',$xhtml_url); ?>'" />

<?php

}elseif($registration_type !="individual"){

?>
   <input type="button" name="billingInfo"  value="<?php echo JText::_( 'DT_BACK' ); ?>" class="button" onclick="window.location='<?php echo  JRoute::_('index.php?option=com_dtregister&eventId='.$eventId.'&Itemid='.$Itemid.'&task=event_register&type=reg_options&back=1&from=1',$xhtml_url); ?>'" />

<?php

}

?>

		<input type="button" name="billingInfo" id="next" value="<?php echo JText::_( 'DT_NEXT_BUTTON' ); ?>" class="button" onclick="validatedetails();" /></td></tr>

		</table>

</form>
<?php
if(${$field_used._s_country}){
?>
<script type="text/javascript">
    //<![CDATA[
	if(typeof(document.frmcart.country) != 'undefined')
	document.frmcart.country.value = "<?php echo isset($rowProfile->cb_country)?$rowProfile->cb_country:''; ?>";
	//]]>
</script>
<?php
}

$document	=& JFactory::getDocument();
$document->addStyleSheet(JURI::root(true).'/components/com_dtregister/assets/css/jquery.lightbox.css');
 
$document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.js');
$document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/textareaCounter.js');

$document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.lightbox.js');
?>
	
<script language="JavaScript" type="text/javascript">
    //<![CDATA[

    //jQuery.noConflict();
	DTjQuery(function(){
	DTjQuery('body').keypress(function(e){
	   
	  
	   if(e.keyCode == 13 && e.originalTarget.type != 'textarea'){
		   validatedetails();
		   return false
	   }else{
		   return true ;
	   }
	   	
	});
  DTjQuery('.upload').live('click',function(){
	   
	   DTjQuery(this.form).attr('target','fileupload');
	   prevtask = DTjQuery(this.form.task).val();
	   prevtype = DTjQuery(this.form.type).val();
	   var filesizes = DTjQuery(this).attr('filesize');
	   var filetype = DTjQuery(this).attr('filetype');
	   var name = DTjQuery(this).attr('filename');
	  
	   DTjQuery(this.form.type).val(name+'|'+filesizes+'|'+filetype);
	   
	   DTjQuery(this.form.task).val('fileupload');
	   DTjQuery(this.form.option).val('com_dtregister');
	   DTjQuery(this.form.option).val('com_dtregister');
	   
	   DTjQuery(this.form).submit();
	   
	   DTjQuery(this.form.task).val(prevtask);
	   DTjQuery(this.form.type).val(prevtype);
	   DTjQuery(this.form).attr('target','');
	   return false;
	});
})
	
	DTjQuery(function(){
    
<?php

 if($terms_conditions)

    {

    ?>

		DTjQuery("#terms_conditions").click(function(){

			var href = DTjQuery(this).attr('href');
            
			DTjQuery.fn.colorbox({href:DTjQuery(this).attr('href'), open:true,iframe:true,  innerWidth:'50%',innerHeight:'50%' });
			
			return false;

		});

	<?php } ?>

	});

function Get_Cookie( check_name ) {

	var a_all_cookies = document.cookie.split( ';' );

	var a_temp_cookie = '';

	var cookie_name = '';

	var cookie_value = '';

	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )

	{

		// now we'll split apart each name=value pair

		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it

		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name

		if ( cookie_name == check_name )

		{

			b_cookie_found = true;

			// we need to handle case where cookie has no value but exists (no = sign, that is):

			if ( a_temp_cookie.length > 1 )

			{

				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );

			}

			// note that in cases where cookie is initialized but no value, null is returned

			return cookie_value;

			break;

		}

		a_temp_cookie = null;

		cookie_name = '';

	}

	if ( !b_cookie_found )

	{

		return null;

	}

}

function Set_Cookie( name, value, expires, path, domain, secure ) {

	// set time, it's in milliseconds

	var today = new Date();

	today.setTime( today.getTime() );

	// if the expires variable is set, make the correct expires time, the

	// current script below will set it for x number of days, to make it

	// for hours, delete * 24, for minutes, delete * 60 * 24

	if ( expires )

	{

		expires = expires * 1000 * 60 * 60 * 24;

	}

	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only

	var expires_date = new Date( today.getTime() + (expires) );

	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +

		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()

		( ( path ) ? ";path=" + path : "" ) +


		( ( domain ) ? ";domain=" + domain : "" ) +

		( ( secure ) ? ";secure" : "" );

}

// this deletes the cookie when called

function Delete_Cookie( name, path, domain ) {

	if ( Get_Cookie( name ) ) document.cookie = name + "=" +

			( ( path ) ? ";path=" + path : "") +

			( ( domain ) ? ";domain=" + domain : "" ) +

			";expires=Thu, 01-Jan-1970 00:00:01 GMT";

}

Set_Cookie( 'test', 'none', '', '/', '', '' );

if ( Get_Cookie( 'test' ) )

{

	cookie_set = true;

	Delete_Cookie('test', '/', '');

}

// if the Get_Cookie test fails, cookies

//are not enabled for this session.

else

{

	alert("<?php echo JText::_( 'DT_ENABLE_COOKIE' );?>");

	DTjQuery('#next').attr('disabled',true);

	cookie_set = false;

}

	function validatedetails()

	{
        <?php if(${$field_used._s_title} && ${$field_used._r_title}){ ?>

			if(document.frmcart.title.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_TITLE' ); ?>");

				document.frmcart.title.focus();

				return;

			}

		<?php }
		?>
		if(document.frmcart.firstname.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_FNAME' ); ?>");

				document.frmcart.firstname.focus();

				return ;

		}

		if(document.frmcart.lastname.value==""){

					alert ("<?php echo JText::_( 'DT_ENTER_LNAME' ); ?>");

					document.frmcart.lastname.focus();

					return;

		}

		<?php if(${$field_used._s_organization} && ${$field_used._r_organization}){ ?>

			if(document.frmcart.organization.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ORGANIZATION' ); ?>");

				document.frmcart.organization.focus();

				return;

			}

		<?php }

		if(${$field_used._s_address} && ${$field_used._r_address}){?>

			if(document.frmcart.address.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS' ); ?>");

				document.frmcart.address.focus();

				return;

			}

		<?php }
         ?>
		 <?php if(${$field_used._s_address2} && ${$field_used._r_address2}){ ?>

			if(document.frmcart.address2.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS2' ); ?>");

				document.frmcart.address2.focus();

				return;

			}

		<?php }
		?>
		<?php 
		if(${$field_used._s_city} && ${$field_used._r_city}){ ?>

			if(document.frmcart.city.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_CITY' ); ?>");

	    	document.frmcart.city.focus();

			return;

			}

		<?php }

		if(${$field_used._s_state} && ${$field_used._r_state}){ ?>

			if(document.frmcart.state.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_STATE' ); ?>");

			document.frmcart.state.focus();

			return;

			}

		<?php }

		if(${$field_used._s_zip} && ${$field_used._r_zip}){ ?>

			if(document.frmcart.zip.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ZIP' ); ?>")

			document.frmcart.zip.focus();

			return false;

			}

		<?php } ?>

		if(document.frmcart.email.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

			document.frmcart.email.focus();

			return;

		}

		if (document.frmcart.cemail.value==""){

	    	alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

	    	document.frmcart.cemail.focus();

		    return;

		}

		if(document.frmcart.email.value!=document.frmcart.cemail.value)	{

			alert("<?php echo JText::_( 'DT_EMAIL_MATCH' ); ?>");

			document.frmcart.cemail.focus();

			return;

		}

		if(document.frmcart.email.value!=""){

			var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

			var returnval=emailfilter.test(document.frmcart.email.value)

			if (returnval==false){

				alert("<?php echo JText::_( 'DT_INVALID_EMAIL' ); ?>");

				document.frmcart.email.select();

				document.frmcart.email.focus();

				return ;

			}

		}

		<?php if(${$field_used._s_phone} && ${$field_used._r_phone}){ ?>

				if(document.frmcart.phone.value==""){

					alert("<?php echo JText::_( 'DT_ENTER_PHONE' ); ?>");

					document.frmcart.phone.focus();

					return;

				}

		<?php }

		if($terms_conditions){?>

			if(!(document.frmcart.terms_conditions.checked)){
               if(DTjQuery(".rokterms_conditions").size()>0){
			      if(DTjQuery(".rokterms_conditions").hasClass('rokchecks-active')){
				       
				  }else{
				     alert("<?php echo JText::_( 'DT_CHECK_TERMS_CONDITIONS_REQUIRE' ); ?>");
					 return ;
				  }
			   }else{
				   alert("<?php echo JText::_( 'DT_CHECK_TERMS_CONDITIONS_REQUIRE' ); ?>");

				   document.frmcart.terms_conditions.focus();

				   return;
				}

			}

		<?php }

	 	//Need to check custom fields here

	echo $dt_evt->javavalidation ;

	 ?>
    <?php
    if(!$userId && $usercreation) {
	?>
	   
	   if (document.frmcart.username.value==""){

	    	alert ("<?php echo JText::_( 'DT_ENTER_USERNAME' ); ?>");

	    	document.frmcart.username.focus();

		    return;

		}
	   
	 	if (document.frmcart.password.value==""){

	    	alert ("<?php echo JText::_( 'DT_ENTER_PASSWORD' ); ?>");

	    	document.frmcart.password.focus();

		    return;

		}
		
			if (document.frmcart.password.value != document.frmcart.confirm_password.value ){

	    	alert ("<?php echo JText::_( 'DT_CONFIRM_PASSWORD_ERROR' ); ?>");

	    	document.frmcart.confirm_password.focus();

		    return;

		}

	<?php 
	
	}
	?>
	 	//Check for a duplicate registration via Ajax request

 	    var email=document.frmcart.email.value;
   
        var username= (typeof(document.frmcart.username) != 'undefined')?document.frmcart.username.value:'';
          
	  	var url="index2.php?option=com_dtregister&task=event_register&type=duplication_check&no_html=1&eventId=<?php echo $eventId;?>&email="+email;
		
		url = "<?php echo JRoute::_('index.php?option=com_dtregister&task=event_register&type=duplication_check&no_html=1&eventId='.$eventId,false)?>&email="+email+"&username="+username;
        
		emailCheck = " ";

		jx.load(url,function(data){

				emailCheck = data;

				switch(parseInt(data)){

					//case "0": // No duplicate... submit form

					//	return;

//					//	break;

					case 1: // Duplicate exists... update email

						alert("<?php echo addslashes(JText::_( 'DT_ALREADY_REGISTERED' )); ?>");

						document.frmcart.email.focus();

						return;

						break;
					
					 case 3: // Duplicate exists... update email

						alert("<?php echo addslashes(JText::_( 'DT_JOOMLA_USERNAME_EXISTS' )); ?>");

						document.frmcart.username.focus();

						return;

						break;
					
					 case 4: // Duplicate exists... update email

						alert("<?php echo addslashes(JText::_( 'DT_JOOMLA_EMAIL_EXISTS' )); ?>");

						document.frmcart.email.focus();

						return;

						break;

					default:

						// now check the captcha security image if needed

					 	var security_image_check=<?php if($security_image_check){echo $security_image_check; } else { echo '0';}?>;

					  	if(security_image_check){

					  		var url='index2.php?option=com_dtregister&task=event_register&type=security_check&eventId=<?php echo $eventId;?>&no_html=1&security_code=';
                            url = "<?php echo JRoute::_('index.php?option=com_dtregister&task=event_register&type=security_check&&no_html=1&eventId='.$eventId,false)?>";
					  		var security_code=document.frmcart.security_code.value;

					  		url=url+ '&security_code='+security_code;

					  		if (security_code==""){

					  			alert("<?php echo addslashes(JText::_( 'DT_ENTER_SECURITY_CODE' )); ?>");

					  			document.frmcart.security_code.focus();

					  			return;

					  		} else {

								jx.load(url,function(data){

									switch(parseInt(data)){

									case 0:

									alert("<?php echo JText::_( 'DT_MISMATCH_SECURITY_IMAGE' ); ?>");

									document.frmcart.security_code.focus();

									return;

									break;

									default:

									document.frmcart.submit();

									return;

									break;

									}

									}

								);

							}

					  	} else {

					  		// not checking security image - submit the form

					  		document.frmcart.submit();

					  	}

						break;

				}

			}

		);

		}
//]]>
</script>

<script language="javascript" type="text/javascript" src="<?php echo $mosConfig_live_site?>/includes/js/joomla.javascript.js"></script>

<script language="javascript" type="text/javascript" src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/jx_dataCheck.js"></script>

<?php

}

// display confirmation of all the

function regGroupUsers ( $option, $eventId ){

  	global $Itemid , $mainframe , $now;

  	$user = &JFactory::getUser();

  	$database = &JFactory::getDBO();

  	$mosConfig_live_site = JURI::base( true );

    include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	?>
    <script language="javascript" type="text/javascript" src="<?php echo $mosConfig_live_site?>/includes/js/joomla.javascript.js"></script>
<script src="<?php echo JURI::root(true); ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>

<script src="<?php echo JURI::root(true); ?>/components/com_dtregister/assets/js/textareaCounter.js" type="text/javascript"></script>
    <?php
    $dt_evt = new Event($eventId);
   	if (isset($_POST['memtot'])){ unset($_SESSION['register']['groupUser']);$_SESSION['register']['memtot']=trim( JRequest::getVar('memtot', '' ) );}

  	$memtot = $_SESSION['register']['memtot'];

	if(isset($_GET['back'])){

		if(isset($_GET['from'])){

		}else{

		  $_SESSION['register']['current_member']--;

		}

		if($_SESSION['register']['current_member'] == 0){

			$url = "index.php?option=com_dtregister&eventId=$eventId&Itemid=$Itemid&task=event_register&type=reg_group_num";

		}else{

			$url="index.php?option=$option&eventId=$eventId&Itemid=$Itemid&task=event_register&type=get_group_users";

		}

		$mainframe->redirect($url);

	 }

  	 $currentMember=$_SESSION['register']['current_member'];

	 if(isset($_SESSION['register']['groupUser'][$currentMember]))

	 $memberdata =  $_SESSION['register']['groupUser'][$currentMember];

  	 if (!$currentMember){$currentMember = 0;}

 		// array to hold all non-custom fields

		$arrFields = array (
            1   =>array('title', JText::_( 'DT_TITLE' ), 'm_s_title', 'm_r_title',JText::_( 'DT_ENTER_TITLE' )),
			2 	=> array('firstname', JText::_( 'DT_FIRSTNAME' ), 'm_s_firstname', 'm_r_firstname',JText::_( 'DT_ENTER_FNAME' )),

			3 	=> array('lastname', JText::_( 'DT_LASTNAME' ), 'm_s_lastname', 'm_r_lastname',JText::_( 'DT_ENTER_LNAME' )),

			4 	=> array('organization', JText::_( 'DT_ORGANIZATION' ), 'm_s_organization', 'm_r_organization',JText::_( 'DT_ENTER_ORGANIZATION' )),

			5 	=> array('address', JText::_( 'DT_ADDRESS' ), 'm_s_address', 'm_r_address',JText::_( 'DT_ENTER_ADDRESS' )),
			
			6  =>array('address2', JText::_( 'DT_ADDRESS2' ), 'm_s_address2', 'm_r_address2',JText::_( 'DT_ENTER_ADDRESS2' )),

			7 	=> array('city', JText::_( 'DT_CITY' ), 'm_s_city', 'm_r_city',JText::_( 'DT_ENTER_CITY' )),

			8 	=> array('state', JText::_( 'DT_STATE' ), 'm_s_state', 'm_r_state',JText::_( 'DT_ENTER_STATE' )),

			9 	=> array('zip', JText::_( 'DT_ZIPCODE' ), 'm_s_zip', 'm_r_zip',JText::_( 'DT_ENTER_ZIP' )),

			10 	=> array('country', JText::_( 'DT_COUNTRY' ), 'm_s_country', 'm_r_country',JText::_( 'DT_ENTER_COUNTRY' )),

			11 	=> array('email', JText::_( 'DT_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			12 	=> array('cemail', JText::_( 'DT_CONFIRM_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			13	=> array('phone', JText::_( 'DT_PHONE' ), 'm_s_phone', 'm_r_phone',JText::_( 'DT_ENTER_PHONE' ))
			
		);

	 //Here is where the discount will be applied

	  $query = "select *,if('". $now->toFormat('%Y-%m-%d')."'>latefeedate,'y','n') as late , if('". $now->toFormat('%Y-%m-%d')."' < bird_discount_date and bird_discount_type<>0 and bird_discount_type <> 3 ,'y','n' ) as bird from #__dtregister_group_event WHERE

	 			eventid=$eventId ORDER BY memberTotal ASC";

	 $database->setQuery($query);

	 $res = $database->loadObjectList();

	 $amountCharged = 0;

	 $latefee =0;

	 $userId=$user->id;

	  $discount=0;

	 foreach($res as $r){

	  $discount_type = $r->discount_type;

	 $discount_amount = $r->discount_amount;

	 $discount=0;

	 	 // memberTotal is 'Number of members' on the admin side

         if($r->bird=='y'){

		    $r->regGroupPerRate = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->regGroupPerRate);

			  $_SESSION['register']['bird_discount'] = 1 ;

		 }

		 if( $memtot >= $r->memberTotal){

		 	if($userId>0){

		 		if($discount_type==1){

		 			$amountCharged = ($r->regGroupPerRate-$discount_amount)* $memtot;

		 			$discount = $discount_amount * $memtot;

		 		} elseif ($discount_type==2){

		 			$amountCharged = $r->regGroupPerRate*(100-$discount_amount) * $memtot/100;

                                        $discount = (($r->regGroupPerRate*$discount_amount)/100) * $memtot;

		 		} else {

		 			$amountCharged = $r->regGroupPerRate * $memtot;

		 		}

				$totalCharged =  $amountCharged;

				$discount = $discount ;

							    if($r->late=='y'){

									$latefee = $r->latefee*$memtot;

				$totalCharged = $latefee + $totalCharged;

								}

				 $_SESSION['register']['amountCharged']=$totalCharged;

				 $discount = $discount;

		 	} else {

		 		$amountCharged = $r->regGroupPerRate * $memtot;

        $totalCharged =  $amountCharged;

			    if($r->late=='y'){

					$latefee = $r->latefee*$memtot;

					$totalCharged = $latefee + $totalCharged;

				}

 $_SESSION['register']['amountCharged']=$totalCharged;

		 	}

		 } else {

	 		break;

		 }

	 }

	 // Load calendar script

	// loop through the post storing values in the SESSION var

	$arrPostVals = array();

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

		$arr = array($value[0]=>$_POST[$value[0]]);

		array_push_associative($arrPostVals,$arr);

	}

?>

<?php

  	$userId=$user->id;

  	if($userId>0)

  	{

  		if($discount_type==1){

  	//echo '<tr><td><div >('.DT_MEMBER_DISCOUNT.' $'.$discount_amount.')</div></td></tr>';

  		}elseif ($discount_type==2){

  	//echo '<tr><td><div >('.DT_MEMBER_DISCOUNT.$discount_amount.'%)</div></td></tr>';

  		}

  	}

  ?>

  <?php

    $arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

				break;

		} else {

			$currency_symbol = NULL;

		}

		}

    ?>

<table class="authorizenetformtable">

<tr><td><?php echo $topmsg; ?></td></tr>

<tr>

	<td>

		<div >

			<?php if($amountCharged > 0){?>

			<?php echo JText::_( 'DT_REGISTRATION_FEE' ); ?>:

			<?php echo $memtot; ?> x <?php echo $currency_symbol. numberFormat(($amountCharged+$discount)/$memtot,2); ?>

			<?php if( ($discount>0)||($latefee>0)) {?>

			<?php if ($discount>0){?> - <?php echo $currency_symbol . numberFormat($discount,2) . '('. JText::_( 'DT_MEMBER_DISCOUNT' ) .')'; } ?>

			<?php if ($latefee>0){?> + <?php echo JText::_( 'DT_LATE_FEE' );?> <?php echo $currency_symbol . numberFormat($latefee,2); } ?> =

			<?php

				if (isset($currency_symbol)){

					echo $currency_symbol . ' ' . numberFormat($_SESSION['register']['amountCharged'],2);

				} else {

					echo numberFormat($_SESSION['register']['amountCharged'],2) . ' ' . $currency_code;

				}

			?>

			<?php } 

			}

			?>

		</div>

	</td>

</tr>

</table>

<table align='center' width='100%' border='0' cellpadding='2' cellspacing='2'>

		<!-- Here we get the general information-->

    	<tr >

		<td colspan="3" align="left" ><strong><?php echo JText::_( 'DT_MEMBER' ) . ' ' . $_SESSION['register']['current_member'] . ' ' . JText::_( 'DT_INFORMATION' ); //$currentMember; ?></strong></td>

		</tr>

		<tr><td colspan="3">( <span class="required">*</span> = <?php echo JText::_( 'DT_REQUIRED_FIELD' );?> )</td></tr>

		<?php

		// loop through the array of possible non-custom fields and show the input box for each

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

			if ($$value[2]){

				if($value[0]=='country'){

					require(JPATH_SITE.'/components/com_dtregister/country.htm');
                }else if($value[0] == 'title'){
				
				    $titles = explode("|",$titleoptions);
			    $temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

			  foreach($titles as $title){
	
				$temp[] = JHTML::_('select.option', $title, $title);
	
			  }
	        
			  $titles = $temp;
				  ?>
				    <tr><td width="30%" class="fieldlabel"><?php echo $value[1] . ' :';

					if ($$value[3]==1){

					?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php

				}

				?></td><td width="68%" align="left" >
                 <?php
				   echo  JHTML::_('select.genericlist',$temp,$value[0], 'class="inputbox" size="1"', 'value', 'text',$memberdata[$value[0]]);
				
				}else{

				?><tr><td width="30%" class="fieldlabel"><?php echo $value[1] . ' :';

					if ($$value[3]==1){

					?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php

				}

					if('cemail'==$value[0]){

						$memberdata['cemail'] = $memberdata['email'];

					}

				?></td><td width="68%" align="left" >

                <input type="text" name="<?php echo $value[0]; ?>" value="<?php echo $memberdata[$value[0]];?>" class="inputbox" />

                <?php }?>

                </td>
                <td width="2%" >&nbsp;</td>
                </tr><?php

			}

		}

	  	//Get Custom Fields
	if(!isset($memberdata)){
	  $memberdata =  array();
	}
        $field_html =  $dt_evt->field_html('M',(object)$memberdata,$showHidden=false,$form='frmcart',false);
	  
	  	if($field_html !="")

	  	{

	  	?>

	      <tr><td colspan="3"><hr /></td></tr>

	  		<tr><td colspan="3"><strong><?php echo JText::_( 'DT_ADDITIONAL_INFORMATION' );?></strong></td></tr>

	  	<?php
            echo $field_html ;
	  		
	  	}

	  	if($currentMember < $memtot ){

	  		$buttonText=JText::_( 'DT_NEXT_MEMBER' );

	  	} else {

	  		$buttonText=JText::_( 'DT_NEXT_BUTTON' );

	  	}

?>

		<tr>

			<td colspan="3">

        <input type="button" onclick="window.location='<?php echo JRoute::_('index.php?option=com_dtregister&eventId='.$eventId.'&Itemid='.$Itemid.'&task=event_register&type=get_group_users&back=1',$xhtml_url); ?>'" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

				<input type="button" name="send" value="<?php echo $buttonText; ?>" class="button" onclick="validateform();" />

			</td>

		</tr>

 </table>

	<input type="hidden" name="type" value="addGroupUser" />

	<input type="hidden" name="latefee" value="<?php echo $latefee?>" />

	<input type="hidden" name="discount" value="<?php echo $discount?>" />

	<input type="hidden" name="amountCharged" value="<?php echo $amountCharged?>" />

  <input type="hidden" name="task" value="event_register" />

  <input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

  <input type="hidden" name="current_member" value="<?php echo $currentMember ;?>" />

	</form>


<script language="JavaScript" type="text/javascript">

//<![CDATA[
DTjQuery.noConflict();
    DTjQuery(function(){
  DTjQuery('.upload').live('click',function(){
	   
	   DTjQuery(this.form).attr('target','fileupload');
	   prevtask = DTjQuery(this.form.task).val();
	   prevtype = DTjQuery(this.form.type).val();
	   var filesizes = DTjQuery(this).attr('filesize');
	   var filetype = DTjQuery(this).attr('filetype');
	   var name = DTjQuery(this).attr('filename');
	  
	   DTjQuery(this.form.type).val(name+'|'+filesizes+'|'+filetype);
	   
	   DTjQuery(this.form.task).val('fileupload');
	   DTjQuery(this.form.option).val('com_dtregister');
	   DTjQuery(this.form.option).val('com_dtregister');
	   
	   DTjQuery(this.form).submit();
	   
	   DTjQuery(this.form.task).val(prevtask);
	   DTjQuery(this.form.type).val(prevtype);
	   DTjQuery(this.form).attr('target','');
	   return false;
	});
})
	
var memberTotal=<?php echo $memtot ;?>;

function validateform()

{

	var currentMember=document.frmcart.current_member.value;
    
	<?php

		if($m_s_title && $m_r_title){	?>

			if(document.frmcart.title.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_TITLE' ); ?>");

			document.frmcart.title.focus();

			return;

			}

	<?php } ?>
	
	<?php if($m_s_firstname && $m_r_firstname){ ?>

			if(document.frmcart.firstname.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_FNAME' ); ?>");

				document.frmcart.firstname.focus();

				return ;

			}

	<?php }

		if($m_s_lastname && $m_r_lastname){	?>

			if(document.frmcart.lastname.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_LNAME' ); ?>");

				document.frmcart.lastname.focus();

				return;

			}

	<?php }

		if($m_s_organization && $m_r_organization){	?>

			if(document.frmcart.organization.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ORGANIZATION' ); ?>");

			document.frmcart.organization.focus();

			return;

			}

	<?php }

		if($m_s_address && $m_r_address){ ?>

			if(document.frmcart.address.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS' ); ?>");

				document.frmcart.address.focus();

				return;

			}

	<?php } ?>
   <?php

		if($m_s_address2 && $m_r_address2){	?>

			if(document.frmcart.address2.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS2' ); ?>");

			document.frmcart.adddress2.focus();

			return;

			}

	<?php } ?>
	
       <?php
		if($m_s_city && $m_r_city){ ?>

			if(document.frmcart.city.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_CITY' ); ?>");

		    	document.frmcart.city.focus();

				return;

			}

	<?php }

		if($m_s_state && $m_r_state)

		{

		?>

			if(document.frmcart.state.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_STATE' ); ?>");

				document.frmcart.state.focus();

				return;

			}

		<?php

		}

		if($m_s_zip && $m_r_zip)

		{

		?>

			if(document.frmcart.zip.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ZIP' ); ?>")

				document.frmcart.zip.focus();

				return false;

			}

		<?php

		}

		if($m_s_email  && $m_r_email)

		{

		?>

			if(document.frmcart.email.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

				document.frmcart.email.focus();

				return;

			}

			if(document.frmcart.cemail.value==""){

		    alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

		    document.frmcart.cemail.focus();

		    return;

			}

			if(document.frmcart.email.value!=document.frmcart.cemail.value){

			alert("<?php echo JText::_( 'DT_EMAIL_MATCH' ); ?>");

			document.frmcart.cemail.focus();

			return;

			}

			if(document.frmcart.email.value!=""){

			var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;

			var returnval=emailfilter.test(document.frmcart.email.value)

				if (returnval==false){

				alert("<?php echo JText::_( 'DT_INVALID_EMAIL' ); ?>");

				document.frmcart.email.select();

				document.frmcart.email.focus();

				return ;

				}

			}

		<?php

		}

		if($m_s_phone && $m_r_phone){ ?>

			if(document.frmcart.phone.value==""){

				alert("<?php echo JText::_( 'DT_ENTER_PHONE' ); ?>");

				document.frmcart.phone.focus();

				return;

			}

		<?php

		}

 		echo $dt_evt->javavalidation ;

	  ?>

		currentMember++;

		document.frmcart.current_member.value=currentMember;

		document.frmcart.task.value="event_register";

		document.frmcart.type.value="addGroupUser";

        // document.frmcart.type.value="save_group";

		document.frmcart.submit();

	}	// END Function validateform()
//]]>
</script>

<?php
  
}

// check the individual/billing info -- confirmation page

function registration_info_check($option, $eventId){
  
	if(isset($_SESSION['register']['billingInfo']) && !isset($_POST['firstname']) ){

		$_POST = $_SESSION['register']['billingInfo'] ; 

		$_POST['amountCharged'] = $_SESSION['register']['amountCharged'];
		
	}
    if(!isset($_SESSION['register']['reg_type']) || $_SESSION['register']['reg_type']==""){
	    
		$_SESSION['register']['reg_type'] = $_GET['type'] ;
	}
	global $Itemid;

	$user = &JFactory::getUser();

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
    if(!$user->id &&  isset($_POST['username']) && $usercreation==1){
	     
		 $_SESSION['register']['joomlauser']['username'] = $_POST['username'] ;
		 $_SESSION['register']['joomlauser']['password'] = $_POST['password'] ;
		 
	}
	// array to hold all non-custom fields

	$arrFields = array (

		1 	=> array('title', JText::_( 'DT_TITLE' ), 'm_s_title', 'm_r_title'),

		2 	=> array('firstname', JText::_( 'DT_FIRSTNAME' ), 'm_s_firstname', 'm_r_firstname'),

		3 	=> array('lastname', JText::_( 'DT_LASTNAME' ), 'm_s_lastname', 'm_r_lastname'),

		4 	=> array('organization', JText::_( 'DT_ORGANIZATION' ), 'm_s_organization', 'm_r_organization'),

		5 	=> array('address', JText::_( 'DT_ADDRESS' ), 'm_s_address', 'm_r_address'),
		
		6 	=> array('address2', JText::_( 'DT_ADDRESS2' ), 'm_s_address2', 'm_r_address2'),

		7 	=> array('city', JText::_( 'DT_CITY' ), 'm_s_city', 'm_r_city'),

		8 	=> array('state', JText::_( 'DT_STATE' ), 'm_s_state', 'm_r_state'),

		9 	=> array('zip', JText::_( 'DT_ZIPCODE' ), 'm_s_zip', 'm_r_zip'),

		10 	=> array('country', JText::_( 'DT_COUNTRY' ), 'm_s_country', 'm_r_country'),

		11 	=> array('email', JText::_( 'DT_EMAIL' ), 'm_s_email', 'm_r_email'),

		// 10 	=> array('cemail', JText::_( 'DT_CONFIRM_EMAIL' ), 'm_s_email', 'm_r_email'),

		12	=> array('phone', JText::_( 'DT_PHONE' ), 'm_s_phone', 'm_r_phone')

	);

		//***************************

		//Get custom fields and store in CustomFields array
			$fld = new Custom_field();
			$fields=array() ;
			$userType = $_SESSION['register']['reg_type'];

		   if ($userType=='reg_individual'){$type='I';}else if($userType=='reg_group'){$type='B';}
		   
            $fld->getAllFields($eventId,$type,false,0,$fields) ;
			
			$rowCustoms = $fields ;
			
			
		/*

		 * When coming back to this page the custom fields get added again

		*/

		$customFee = 0;

		//	Add custom fields fee to amount charged
       
		for($i=0,$n=count($rowCustoms);$i<$n;$i++){

			$rowCustom=$rowCustoms[$i];

			if(!$rowCustom->fee_field){ continue; }

			$name=$rowCustom->name;

			$customType=$rowCustom->type;

			$values=$rowCustom->values;

			$arrValues=explode("|",$values);

			$fees=$rowCustom->fees;

			$arrFees=explode("|",$fees);

			$postedValue=JRequest::getVar($name,'','post');
            if(!is_array($postedValue)){
			   $postedValue = explode(",",$postedValue);
			}
			
			for($j=0,$m=count($arrValues);$j<$m;$j++){

				if($customType==3){
                
				  
					if(in_array(trim($arrValues[$j]),$postedValue)){
                      
						$customFee+=$arrFees[$j];

					}

				} else {

					if(trim($arrValues[$j])==$postedValue){

						$customFee+=$arrFees[$j];

						break;

					}

				}

			}
			
		}

         $dt_event = new Event ($eventId);

		 $customFee = $dt_event->get_custom_fields_fee((object)$_POST,$type);
		 
		$arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

				break;

		} else {

			$currency_symbol = NULL;

		}

		}

		// get all of the fee and custom fees

		$amountCharged = JRequest::getVar('amountCharged','','post'); // registration fee
        
		if ($_SESSION['register']['memtot'] > 1){

			$groupFee = 0;

			foreach($_SESSION['register']['groupUser'] as $key=>$value){

				$groupFee += $_SESSION['register']['groupUser'][$key]['customFee'];

			}

		}

		$customFee += $groupFee;

		?>

			<table>

			<tr>

				<td colspan="2"><?php echo JText::_( 'DT_CONFIRM_PAGE_HELP' ); ?></td>

			</tr>

			<tr> <td colspan="2">&nbsp;</td></tr>

      <tr><td colspan="2">

      <strong>

			<?php
          
			$discount_code_amount = 0;
            
			$temp = ($amountCharged+$customFee);
			
			if ($temp > 0){
                
				//require_once('class.dtregister.php');

				$dt_user = new DT_User(null, $eventId);

				$valid = $dt_user->validate_code(JRequest::getVar('discount_code','','post'));

				if($valid){

					$dt_user->set_discount_code(JRequest::getVar('discount_code','','post'));

					$dt_code = new DiscountCode($dt_user->discount_id);

					$discount_code_amount = $dt_code->get_discount_amount($amountCharged+$customFee);

					$_SESSION['register']['discount_code_id'] = $dt_user->discount_id;

				}

			?>

				<?php echo JText::_( 'TOTAL_REGISTRATION_COST' );?>:

        <?php
		   $total_discount = $dt_user->event->getTotalDiscount(($amountCharged+$customFee-$discount_code_amount));
                
				//$amountCharged -= $total_discount ;
			$tax_amount = $dt_user->event->getTaxAmount(($amountCharged+$customFee-$discount_code_amount-$total_discount));
			
			if (isset($currency_symbol)){

				echo $currency_symbol . ' ' . numberFormat($amountCharged+$customFee-$discount_code_amount-$total_discount+$tax_amount ,2);

			  } else {

				echo numberFormat($amountCharged+$customFee-$discount_code_amount+$tax_amount ,2) . ' ' . $currency_code;

			  }
			  if($tax_amount > 0){
			      echo ' ('.JText::_( 'DT_INCLUDES' ).' '.$dt_user->event->tax_amount.'% '.JText::_( 'DT_TAX_OF' ).' '.numberFormat($tax_amount,2).')' ;
			  }
			  if(isset($_SESSION['register']['discount']) && (float)$_SESSION['register']['discount'] >0){
			      
				  echo ' ('.JText::_( 'DT_MEMBER_DISCOUNT' ).')' ;
				  
			  }
			    
                   if(isset($_SESSION['register']['bird_discount'])){

		                 echo ' ('. JText::_( 'DT_BIRD_RATE' ).')' ;

		           }
                
				?></strong><br />

				( <?php echo JText::_( 'DT_EVENT_FEES' ) . ' = ' . numberFormat($amountCharged,2) . '; ' . JText::_( 'DT_ADDITIONAL_FEES' ) . ' = ' . numberFormat($customFee,2); 
				if(($dt_user->event->bird_discount_type == 3 ||  $dt_user->event->discount_type ==3) && $total_discount > 0){
				  
				   echo "; ".JText::_( 'DT_TOTAL_DISCOUNT' ). " = ".numberFormat($total_discount,2) ;
				  
				}
				?>)<br />

			</td></tr>

			 <?php
            $amountCharged -= $total_discount ;
			$amountCharged += $tax_amount ;
            if($discount_code_amount > 0){

			?>

			<tr><td colspan="2"><strong><?php echo JText::_( 'DT_DISCOUNT_CODE_APPLIED'); ?>: <?php echo isset($currency_symbol)?$currency_symbol.' '.numberFormat($discount_code_amount,2):numberFormat($discount_code_amount,2).' '.$currency_code?></strong></td></tr>

            <tr></tr>

            <?php

            }else if(isset($dt_user->discountcode->error) && $dt_user->discountcode->error != ""){

			   ?>

                <tr><td colspan="2"><strong><?php echo $dt_user->discountcode->error ;?></strong></td>
                
            <?php
			}
    $dt_user->event->read();
	        $temp = ($amountCharged+$customFee) ;
			
			$minimum_amount_js = "";
            if($dt_user->event->partial_payment ==1 && $temp > 0){
			?>

			<tr><td><?php  echo JText::_( 'DT_DEPOSIT_AMOUNT'); ?></td>
               <td><input type="text" name="partial_payment" value="" />
               
              ( <?php  echo JText::_( 'DT_MINIMUM_DEPOSIT'); ?> = 

               <?php echo isset($currency_symbol)?$currency_symbol.' '.numberFormat($dt_user->event->partial_minimum_amount,2):numberFormat($dt_user->event->partial_minimum_amount,2).' '.$currency_code?> )
			   
               <?php
				 if($dt_user->event->partial_minimum_amount!="" && $dt_user->event->partial_minimum_amount  > 0 ){
                   $minimum_amount_js = 'if(form.partial_payment.value < '.$dt_user->event->partial_minimum_amount.'){ alert("'.JText::_( 'DT_MINIMUM_AMOUNT_ERROR').'") ; return ;}';
			     }
			   ?>
                
                </td>
            
            </tr>

            <tr></tr>

            <?php

            }else if($dt_user->event->partial_payment == 2 && $temp > 0){
			 ?>
             <tr>
               <td>
                 <input type="hidden" value="<?php echo $dt_user->event->partial_amount; ?>" name="partial_payment" />
                  ( <?php  echo JText::_( 'DT_DEPOSIT_AMOUNT'); ?> = 

               <?php echo isset($currency_symbol)?$currency_symbol.' '.numberFormat($dt_user->event->partial_amount,2):numberFormat($dt_user->event->partial_amount,2).' '.$currency_code?> )
               </td>
             </tr>
             <?php
			}

		?>
 
		<?php

			}

			$_SESSION['register']['discount_code_amount'] = str_replace(",",".",numberFormat($discount_code_amount,2));

		// loop through the array

		// - store and display the post values from billingInfo

		$arrGetFields = array();

        global $states;

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

			foreach ($_POST as $key2=>$value2){

				if ($value[0] == $key2){

					/*if($key2=="state" && $_POST['country']=='United States' && strlen($value2) > 2){

						$value2 = $states[strtoupper($value2)];

					}*/

					$val = array($value[0]=>$value2);

					array_push_associative($arrGetFields,$val);

					?>

					<tr>

						<td valign="top"><?php echo stripslashes($value[1]); ?>: </td>

						<td><?php echo stripslashes($value2); ?></td>

					</tr>

					<?php

				}

			}

		}
        if(isset($_SESSION['register']['joomlauser']['username']) && $_SESSION['register']['joomlauser']['username'] !=""){
		   
		   ?>

					<tr>

						<td valign="top"><?php echo JText::_('DT_USERNAME'); ?>: </td>

						<td><?php echo $_SESSION['register']['joomlauser']['username']; ?></td>

					</tr>

					<?php
		   
		}
  		$arrGetCustom = array();

		for($i=0,$n=count($rowCustoms);$i<$n;$i++){

			$rowCustom=$rowCustoms[$i];

			/*if($_SESSION['register']['reg_type']=="reg_group"){

				if($rowCustom->group_behave==1){

					continue;

				}

			}*/

			$name=$rowCustom->name;

			$type=$rowCustom->type;

			$value=JRequest::getVar($name,'','post');
         
			if((!isset($value) || trim(stripslashes($value))=="") && $type !=6){

				continue;

			}
            
			if($type==3 && is_array($value)){

				$value=implode(', ',$value);

			}

			$val = array($name=>$value);

			array_push_associative($arrGetFields,$val);

			if($i==0){

			?>

				<tr><td colspan="2"><hr /></td></tr>

	  		<tr><td colspan="2" ><strong><?php echo JText::_( 'DT_ADDITIONAL_INFORMATION' );?></strong></td></tr>

	  		<?php

			}

			if($rowCustom->type != "" && (stripslashes($value)!="" || $type == 6)){
            
	  		?>

			<tr>
               <?php
                 if($rowCustom->type == 6){
				    echo "<td colspan='2'>" . stripslashes($rowCustom->textual) . "</td>";
				 }else{
			   ?>
				<td valign="top" class="fieldlabel"><?php echo stripslashes($rowCustom->label); ?></td>

				<td><?php echo nl2br(stripslashes($value)); ?></td>
                <?php 
				 }
				?>
			</tr>

			<?php

			}

		}
 
	$_SESSION['register']['billingInfo'] = $arrGetFields;

  	$_SESSION['register']['billingInfo']['customFee'] = $customFee;
    
		// END Get custom fields

		//***************************

		?>

	  	<?php
 
		$userType = $_SESSION['register']['reg_type'];

		if ($userType=='reg_individual'){$userType='I';}else if($userType=='reg_group'){$userType='G';}

		if ($userType == 'G'){

	    echo '<tr><td colspan="2"><hr /></td></tr>';

	  	echo '<tr><td colspan="2"><strong>' . JText::_( 'DT_GROUP_INFO' ). '</strong></td>';

		$sql = "select fb.id as key1,   fb.* , f.id as key2 , f.* From #__dtregister_fields f, #__dtregister_field_event fb where f.id = fb.field_id and f.published=1 and f.hidden = 0 and (fb.showed=1 or (fb.showed =2 and f.showed=1)) and fb.event_id='".$eventId."' order by f.ordering";

		$database->setQuery($sql);

		$rows=$database->loadObjectList();
        $fld = new Custom_field();
		$fields=array() ;
        $fld->getAllFields($eventId,'M',false,0,$fields) ;
			
		$rows = $fields ;
		$customrows = array();
      
		if($rows){

			foreach($rows as $value){

				if($value !=""){

					$customrows[$value->name] = $value;

				}

			}

		}
		    
            $lables =  array(
			 'title'=>JText::_( 'DT_TITLE'),
		     'firstname'=>JText::_( 'DT_FIRSTNAME'),
			 'lastname'=>JText::_( 'DT_LASTNAME'),
			 'city'=>JText::_( 'DT_CITY'),
			 'state'=>JText::_( 'DT_STATE'),
			 'address'=>JText::_( 'DT_ADDRESS'),
			 'address2'=>JText::_( 'DT_ADDRESS2'),
			 'zip'=>JText::_( 'DT_ZIPCODE'),
			 'email'=>JText::_( 'DT_EMAIL'),
			 'country'=> JText::_( 'DT_COUNTRY' ),
			 'organization'=> JText::_( 'DT_ORGANIZATION' ),
			 'phone'=> JText::_( 'DT_PHONE' )
			);
			foreach ($_SESSION['register']['groupUser'] as $key => $value){

				echo "<tr><td colspan=2><br /><u>".JText::_( 'DT_MEMBER' )." {$key}</u></td></tr>";
				
				foreach ($value as $key2 => $value2){
                    
					if($key2 !== "customFee"){

						if($value2!=''){

							if(isset($customrows[$key2])){

								//if($customrows[$key2]->group_behave==1 || $customrows[$key2]->group_behave==3){

									if($customrows[$key2]->type==3){

										$value2 = str_replace('|',', ',$value2);

									}
                                    if($customrows[$key2]->type==6){
										
										echo "<tr><td colspan='2'>" . stripslashes($customrows[$key2]->textual) . "</td></tr>";
									   	
									}else{
									echo "<tr><td>" . stripslashes($customrows[$key2]->label) . ": </td><td>". stripslashes($value2) ."</td></tr>";
									}

								//}

							}else{
                                  if(isset($lables[$key2])){
								   $label = $lables[$key2];
								 }else{
								   $label = stripslashes($key2);
								 }
								echo "<tr><td>" . stripslashes($label) . ": </td><td>". htmlentities(stripslashes($value2),null,'UTF-8')  ."</td></tr>";

							}

						}

					}

				}

			}

		}

	  	?>

		<tr><td colspan="2" align="center">&nbsp;</td></tr>

		<tr><td colspan="2" align="center">

		<input type="hidden" name="task" value="" />

		<input type="hidden" name="type" value="" />

		<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

		<input type="hidden" name="eventId" value="<?php echo $_SESSION['register']['eventId']; ?>" />

		<input type="hidden" name="reg_info_check" value="1" />

		<input type="hidden" name="back_from_confirm" value="1" />

		<input type="hidden" name="amountCharged" value="<?php echo $amountCharged;  $_SESSION['register']['amountCharged'] = $amountCharged; ?>" />

		<input type="hidden" name="customFee" value="<?php echo $_SESSION['register']['billingInfo']['customFee']; ?>" />

		<input type="button" name="back" value="<?php echo JText::_( 'DT_BACK' ); ?>" class="button" onclick="backToPrePage();" />

		<input type="button" name="send" value="<?php echo JText::_( 'DT_NEXT_BUTTON' ); ?>" class="button" onclick="sendPayment();" /></td></tr>

		</table>

		</form>

	<script language="javascript" type="text/javascript">
         //<![CDATA[
		 function backToPrePage(){

			var form=document.frmcart;

			form.task.value="event_register";

			<?php if ($_SESSION['register']['memtot'] > 1){ ?>

				form.type.value="reg_group_billing";

			<?php } else { ?>

				form.type.value="reg_individual";

			<?php } ?>

			form.submit();

		 }

		function sendPayment(){

			var form=document.frmcart;

			var amountCharged=form.amountCharged.value;

			var customFee=form.customFee.value;

			var totalFee=<?php echo $amountCharged + $customFee - $discount_code_amount; ?>;
            
			<?php
			echo $minimum_amount_js ;
			?>
			
			if( totalFee > 0){

				form.task.value="payment";

				form.type.value="";

			}else if (totalFee <= 0){

				form.task.value="payment";

				form.type.value="free";

			}

			form.submit();

		}
     //]]>
	</script>

	<?php
	
}

//}

// Form displayed to get the group size

// upon completion this forwards to groupdetails()

function getGroupNum($option, $eventId){

  	global $Itemid;

  	$database = &JFactory::getDBO();

  	$mosConfig_live_site = JURI::base( true );

  	require_once(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

  	$availableSpots=getAvailableSpots($eventId);

  	$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	$eventName=$database->loadResult();

	$sql="SELECT max_group_size FROM #__dtregister_group_event WHERE eventId={$eventId}";

	$database->setQuery($sql);

	$max_group_size=$database->loadResult();

  ?>

  <table><tr><td><?php echo JText::_( 'GROUP_NUMBER' );?>: </td><td><input type="text" size="4" name="memtot" /></td> </tr>

  <tr><td colspan="2"><input type="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' );?>" class="button" onclick="groupdetails();" /></td></tr>

  </table>

  <input type="hidden" name="option" value="<?php echo $option;?>" />

  <input type="hidden" name="task" value="event_register" />

  <input type="hidden" name="eventId" value="<?php echo $eventId;?>" />

  <input type="hidden" name="Itemid" value="<?php echo $Itemid;?>" />

  <input type="hidden" name="type" value="get_group_users" />

  </form>

  <script type="text/javascript">
    //<![CDATA[
	  function groupdetails(){

	  	// check that there is a value and it is a number

		  var spots=<?php echo $availableSpots?>;

		  var max=<?php echo $max_group_size==''?0:$max_group_size; ?>;

		  if(document.frmcart.memtot.value== '' || document.frmcart.memtot.value.charAt(0)==''|| isNaN(parseInt(document.frmcart.memtot.value))){

		  	alert("<?php echo JText::_( 'GROUP_NUMBER' ); ?>");

		  	return;

	  	  }

	  // check that the number is less than the number of available spots

	  if(spots!=-1){

		  if(document.frmcart.memtot.value>spots){

		  alert("<?php echo JText::_( 'DT_THERE_ARE_ONLY' ); ?> "+spots +" <?php echo JText::_( 'DT_AVAIL_REGISTER_SPOTS' ); ?>");

		  return;

		  }

	  }

	  if(document.frmcart.memtot.value > max && max !=0){

	  	alert("<?php echo JText::_( 'DT_MAX_GROUP_REGISTRATIONS' ); ?>"+max);

	  	return;

	  }

	  // check that the number is more than one

		if(document.frmcart.memtot.value<2)	{

			alert("<?php echo JText::_( 'DT_REGISTRANTS_MORE_THAN_ONE' ); ?>");

			return false;

		}

	  document.frmcart.submit();

  }
    //]]>
  </script>

  <?php

  	// set current memter to 1 for group registrations

	$_SESSION['register']['current_member'] = 1;

}

// Let the user select if this is an individual or group registration and redirect accordingly

function reg_options($option, $eventId){

	global $topdon, $topexp, $lastdon, $lastexp,$Itemid;

    include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	//Get the event name

	$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	$eventName=$database->loadResult();

?>

		<table class="message">

			<tr align="center"> <td colspan="2"><span ><strong><?php echo JText::_( 'SELECT_OPTION' );?> </strong></span><br /></td></tr>

			<tr>

      <td align="center" width="50%">

              <div>
                
               <a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&eventId='.$eventId.'&task=event_register&type=reg_individual',$xhtml_url ); ?>" > <img src="<?php echo  JURI::root(true);?>/components/com_dtregister/assets/images/individual.jpg" alt="" vspace="5" border="0" width="120" height="100" /></a>

             </div>

            </td>

		<td align="center" width="50%">

              <div align="center">
               
               <a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&eventId='.$eventId.'&task=event_register&type=reg_group_num',$xhtml_url ) ?>" > <img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/group.jpg" alt="" vspace="5" border="0" width="120" height="100" /></a>

             </div>

            </td>

           </tr>

			<tr><td width="50%" align="center"><div><input name="rtype" type="radio" value="individual" />

	     	<?php echo JText::_( 'INDIVIDUAL_REGISTRATION' );?> </div></td>

          <td align="center"><div><input name="rtype" type="radio" value="group" /><input type="hidden" name="eventId" value="<?php echo $eventId?>" />

          	<?php echo JText::_( 'GROUP_REGISTRATION' );?></div></td></tr>

			<tr><td colspan="2" align="center">&nbsp; </td></tr>

			<tr><td colspan="2" align="center"><div><input type="button" name="send" value="<?php echo JText::_( 'DT_NEXT_BUTTON' ); ?>" class="button" onclick="validateit();" /></div></td></tr>

		</table>

		<input type="hidden" name="type" value="" />

		<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

		</form>

		<script type="text/javascript">
           //<![CDATA[
			function validateit()

			{

				if(document.frmcart.rtype[0].checked==false && document.frmcart.rtype[1].checked==false){

					alert ("Please Select any type first");

					document.frmcart.rtype[0].focus();

			    	return;

			    }

				if(document.frmcart.rtype[0].checked){

					<?php // $_SESSION['register']['reg_type'] = 'reg_individual';	$_SESSION['register']['memtot'] = 1; ?>
                      
					window.location ="<?php echo  JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&eventId='.$eventId.'&task=event_register&type=reg_individual',false ) ; ?>";

				} else if(document.frmcart.rtype[1].checked){

					<?php // $_SESSION['register']['reg_type'] = 'reg_group';	$_SESSION['register']['memtot'] = NULL; ?>

			    	window.location ="<?php echo  JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&eventId='.$eventId.'&task=event_register&type=reg_group_num',false ) ?>";

				} else {

					return;

				}

			}
           //]]>
		</script>

<?php

}

// display what payment options the users have and redirect accordingly

// payment options include: Authorizenet, Echeck, Paypal and Pay Later

function payOptions(){

	global $Itemid , $mainframe;

    if(isset($_SESSION['register']['billingInfo']['cardtype'])){

	   unset($_SESSION['register']['billingInfo']['cardtype']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_card_num'])){

	   unset($_SESSION['register']['billingInfo']['x_card_num']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_exp_date'])){

	   unset($_SESSION['register']['billingInfo']['x_exp_date']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_card_code'])){

	   unset($_SESSION['register']['billingInfo']['x_card_code']);

	}

	if(isset($_SESSION['register']['paymentMethod'])){

	   unset($_SESSION['register']['paymentMethod']);

	}

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

 	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

  $event_Id = $_SESSION['register']['eventId'];

	$evt = new Event($event_Id);

  $evt->over_ride_global();

	$arrPaymentMethods=explode(",",$paymentmethod);
   	// if only one payment option then skip that page and go directly to that payment method
  $type=JRequest::getVar('type','','post');
	if (count(array_filter($arrPaymentMethods)) == 1 && $type !="back"){

		// need to stay here if it's a pay later option - need to select the option

		if(!in_array("pay_later",$arrPaymentMethods)){

		// redirect to that payment option

			if (!headers_sent()) {

				$mainframe->redirect( $mosConfig_live_site.'/index.php?option=com_dtregister&task=payment&Itemid='.$Itemid.'&type='.$arrPaymentMethods[0].'&eventId='.$_SESSION['register']['eventId']);

			}

		}else{
		   $arrSelected =  explode(",",$pay_later_options);
		 
		   if(count($arrSelected) == 1){
		      //redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=pay_later&eventId="+eventId+"&pay_later_option="+payLaterOption;
			  	$mainframe->redirect( $mosConfig_live_site.'/index.php?option=com_dtregister&task=payment&Itemid='.$Itemid.'&type='.$arrPaymentMethods[0].'&eventId='.$_SESSION['register']['eventId'].'&pay_later_option='.$pay_later_options);
		   }
		   
		}

	}

	?>

	<div id="paymentselection" <?php echo ($type=='back')?'style="display:none;"':""; ?> >

	<br />

	<?php echo JText::_( 'SELECT_PAYMENT_OPTION' );?>

	<table class="message">

		<?php

		//Authorize.net payment method

		if(in_array("authorizenet",$arrPaymentMethods)){?>
             
        <tr> 
            <td valign="top" width="164">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/card_pay.jpg" alt="" width="149" height="100" align="middle" />
			</td>
             <td valign="top" ><input type="radio" id="paymentmethod1" name="paymentmethod" value="authorizenet" checked="checked" /><?php echo JText::_( 'AUTH_NET' );?></td>
           </tr>
        		
		<?php  }

		if(in_array("paypal",$arrPaymentMethods)){ ?>
            
        <tr> 
            <td valign="top" width="164"><img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/paypal_pay.jpg" width="149" alt="" height="100" align="middle" /></td>
             <td valign="top" ><input type="radio" id="paymentmethod2" name="paymentmethod" value="paypal" /><?php echo JText::_( 'PAYPAL' );?></td>
           </tr>
        
		<?php }

		if(in_array("echeck",$arrPaymentMethods)){ ?>
           
           <tr> 
            <td valign="top" width="164"><img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/echeck_pay.jpg" width="149" height="100" align="middle" alt="" /></td>
             <td valign="top" ><input type="radio" id="paymentmethod3" name="paymentmethod" value="echeck" /><?php echo JText::_( 'ECHECK' );?></td>
           </tr>
        
		<?php }

        if(in_array("ideal",$arrPaymentMethods)){ ?>
               
          <tr> 
            <td valign="top" width="164"><img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/ideal_pay.jpg" width="149" height="100" align="middle" alt="" /></td>
             <td valign="top" ><input type="radio" id="paymentmethod4" name="paymentmethod" value="ideal" /><?php echo JText::_( 'DT_IDEAL' );?></td>
           </tr>
	  <?php }
		
		?>
        <?php
       if(in_array("idealRabo",$arrPaymentMethods)){ ?>
          
           <tr> 
            <td valign="top"  width="164"><img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/ideal_pay.jpg" width="149" height="100" align="middle" alt="" /></td>
             <td valign="top" ><input type="radio" id="paymentmethod5" name="paymentmethod" value="idealRabo" /><?php echo JText::_( 'DT_IDEAL' );?></td>
           </tr>
       <?php } ?>
        
         <?php
         if(in_array("GoogleCheckout",$arrPaymentMethods)){ ?>
            <tr> 
            <td valign="top"><img src="https://checkout.google.com/buttons/checkout.gif?merchant_id=<?php echo $googlemerchid ;?><?php echo $amp;?>w=160<?php echo $amp;?>h=43<?php echo $amp;?>style=trans<?php echo $amp;?>variant=text<?php echo $amp;?>loc=en_US"  align="middle" alt="" /></td>
             <td valign="top" ><input type="radio" id="paymentmethod6" name="paymentmethod" value="GoogleCheckout" /><?php echo JText::_( 'DT_GOOGLE_CHECKOUT' );?></td>
           </tr>
		<?php } ?>
        
         <?php
         if(in_array("NetDeposit",$arrPaymentMethods)){ ?>
            <tr> 
            <td valign="top" width="164">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/card_pay.jpg" alt="" width="149" height="100" align="middle" />
			</td>
             <td valign="top" ><input type="radio" id="paymentmethod6" name="paymentmethod" value="NetDeposit" /><?php echo JText::_( 'DT_NETDEPOSIT' );?></td>
           </tr>
		<?php } ?>
        
          <?php
         if(in_array("Eway",$arrPaymentMethods)){ ?>
            <tr> 
            <td valign="top" width="164">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/eway_card_pay.jpg" alt="" width="149" height="100" align="middle" />
			</td>
             <td valign="top" ><input type="radio" id="paymentmethod7" name="paymentmethod" value="Eway" /><?php echo JText::_( 'DT_EWAY' );?></td>
           </tr>
		<?php } ?>
		
        <?php
		if(in_array("pay_later",$arrPaymentMethods)){ ?>
             <tr> 
            <td valign="top"  width="164"><img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/pay_later.jpg" width="149" alt="" height="100" align="middle" /></td>
             <td valign="top" >	<input type="radio" id="paymentmethod7" name="paymentmethod" value="pay_later"<?php if (count($arrPaymentMethods) == 1){echo 'checked="checked"';} ?> /><?php echo JText::_( 'DT_PAY_LATER' );?>

				<?php

					$options=array();

					$options[]=JHTML::_('select.option',0, JText::_( 'DT_SELECT_PAY_OPTIONS' ));

					$arrSelected=explode(",",$pay_later_options);

					if(in_array(1,$arrSelected)){

						$options[]=JHTML::_('select.option',1, JText::_( 'DT_PAY_AT_DOOR' ));

					}

					if(in_array(2,$arrSelected)){

						$options[]=JHTML::_('select.option',2, JText::_( 'DT_MAILIN_PAYMENT' ));

					}

					if(in_array(3,$arrSelected)){

						$options[]=JHTML::_('select.option',3, JText::_( 'DT_CALLIN_PAYMENT' ));

					}

					echo JHTML::_('select.genericlist', $options,'pay_later_option','','value','text');

				?>
</td>
           </tr>
	<?php

		}

	?>

	<tr><td>

	<?php // Here is a hidden radio button. It is needed because if only a single radio button is present the JS loop below doesn't know it's selected ?>

	<input type="radio" id="paymentmethod8" name="paymentmethod" value="" style="display: none;"/>

	<input type="button" onclick="backToPrePage();" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

	<input type="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' ); ?>"  class="button" name="submitbtn" onclick="paymentform();" /></td></tr>

	</table>

</div>

	<input type="hidden" name="eventId" value="<?php echo $_SESSION['register']['eventId']; ?>" />

    <input type="hidden" name="task" value="" />

    <input type="hidden" name="type" value="" />

	</form>

	<script type="text/javascript">
    //<![CDATA[
	<?php

		/* check that a payment option has been selected and redirect accordingly	*/
		
		if($type=="back"){
		  ?>
		    
		    backToPrePage();
		  <?php
		}

	?>

     function backToPrePage(){

			var form=document.frmcart;

			form.task.value="event_register";

			<?php if ($_SESSION['register']['memtot'] > 1){ ?>

				form.type.value="reg_info_check";

			<?php } else { ?>

				form.type.value="reg_info_check";

			<?php } ?>

			form.submit();

		 }

	function paymentform(){

	 	var paymentMethod="";

	 	var live_site="<?php echo $mosConfig_live_site; ?>";

	 	var eventId="<?php echo $_SESSION['register']['eventId']; ?>";

	 	var Itemid="<?php echo $_SESSION['register']['Itemid']; ?>";

	 	// Get payment method now

		for (i=0;i<document.frmcart.paymentmethod.length;i++){

 			if (document.frmcart.paymentmethod[i].checked==true) {

           	var paymentMethod = document.frmcart.paymentmethod[i].value;

         		break;

        	}

    	}

    	<?php

//    		if (count($arrPaymentMethods) == 1){

//    			if(in_array("pay_later",$arrPaymentMethods)){

//    				echo 'paymentMethod="pay_later;"';

//    			}

//    		}

    		?>

		if(paymentMethod==""){

			alert("<?php echo JText::_( 'DT_SELECT_PAY_OPTIONS' ); ?>");

		 	return;

		}

	 	switch(paymentMethod){
            
			case "Eway":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=Eway&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;
			case "NetDeposit":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=NetDeposit&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;
			
			case "GoogleCheckout":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=GoogleCheckout&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;
			
	 		case "authorizenet":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=authorizenet&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;

		 	case "paypal":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=paypal&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;

		 	case "echeck":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=echeck&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;

		  	case "ideal":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=ideal&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

		 		break;
			case "idealRabo":

			redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=idealRabo&Itemid=<?php echo $Itemid ?>&eventId="+eventId;

			break;

		 	case "pay_later":

				payLaterOption=document.frmcart.pay_later_option.value;

		 		if(payLaterOption==0){

		 			alert("<?php echo JText::_( 'DT_SELECT_PAY_LATER_OPTION' ); ?>");

		 			return;

		 		}

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=payment&type=pay_later&Itemid=<?php echo $Itemid ?>&eventId="+eventId+"&pay_later_option="+payLaterOption;

		 		break;

		 	default:

		 		// alert("<?php echo JText::_( 'DT_SELECT_PAYMENT_METHOD' ); ?>");

		 		break;

		}

		redirectUrl=redirectUrl + "&Itemid=<?php echo $Itemid;?>";

	 	location.href=redirectUrl;

	 }

	//]]>
    </script>

	<?php

}

function paypal_payfailure($option){

	$mosConfig_live_site = JURI::base( true );

/*	$userId=mosGetParam($_REQUEST,'user_id',0);

	// payment is not verified.

	$sql = "UPDATE #__dtregister_user SET payment_verified=0 WHERE userId=$userId";

	$database->setQuery($sql);

	$database->query();

*/

	/*

	// remove the user from the DB because the payment was cancelled

	// get groupId for this user

	$sql="SELECT groupId FROM #__dtregister_group WHERE useid=$userId";

	$database->setQuery($sql);

	$gid=$database->loadResult();

	// remove from dtregister_user

	$sql="DELETE FROM #__dtregister_user WHERE userId=$userId";

	$database->setQuery($sql);

	$database->query();

	// remove from dtregister_group_amount

	$sql="DELETE FROM #__dtregister_group_amount WHERE groupId=$gid";

	$database->setQuery($sql);

	$database->query();

	// remove from dtregister_group

	$sql="DELETE FROM #__dtregister_group WHERE groupId=$gid";

	$database->setQuery($sql);

	$database->query();

	// remove from dtregister_group_member

	$sql="DELETE FROM #__dtregister_group_member WHERE groupUserId=$gid";

	$database->setQuery($sql);

	$database->query();

	*/

	$msg .= '<h3>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</h3>';

	echo $msg.'<a href="'. JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a>';

}

function paypal_payreturn($option){

	 $database = &JFactory::getDBO();

	/*$data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			 $sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);

	        $userId=$row[0]->user_id;

	        $_SESSION = $data;
              $_SESSION['register']['billingInfo']['transaction_id'] = $_REQUEST['txn_id'] ;
			if($userId ==0){

			    $userId = saveInfo('Paypal',1);

				$sql = "update #__dtregister_session set user_id='".$userId."' where id=".$paypal_session_id;

                $database->setQuery($sql);

                $database->query();

                $sql = "update #__dtregister_user set payment_verified=1 , pay_later_paid=1 where userId=".$userId;

                $database->setQuery($sql);

                $database->query();

                registration_email_frontend($userId);

			}*/

	$amount=JRequest::getVar('amount');

	global $DT_mailfrom,$DT_fromname,$Itemid;

	$user = &JFactory::getUser();

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	//Currency symbol

	$arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

			break;

	} else {

		$currency_symbol = NULL;

	}

	}

	// validate the users payment

	//$sql = "UPDATE #__dtregister_user SET payment_verified=1 WHERE userId=$userId";

	//$database->setQuery($sql);

	//$database->query();

	// get info for the emails

	/*$sql="Select * From #__dtregister_user where userId=$userId";

	$database->setQuery($sql);

	$rowUser = $database->loadObject();

	 $address= stripslashes($rowUser->userAddress);

	 $city = stripslashes($rowUser->userCity);

	 $zip = stripslashes($rowUser->userZip);

	 $state = stripslashes($rowUser->userState);

	 $email = stripslashes($rowUser->userEmail);

	 $country = stripslashes($rowUser->userCountry);

	 $fname = stripslashes($rowUser->userFirstName);

	 $lname = stripslashes($rowUser->userLastName);

	 $phone = stripslashes($rowUser->userPhone);

	 $org = stripslashes($rowUser->userOrganization);

	 $eventId = $rowUser->eventId;

	 $userType = $rowUser->userType;*/
	 $userId = 0 ;
	 $eventId = JRequest::getVar('eventId');
     $dt_event = new Event($eventId);
      if($dt_event->thanksmsg_set){
		      $thanksmsg = $dt_event->thanksmsg;
		   }

	// for the custom email

	$contactDetails = $address.'<br />'.$city.', '.$state.' '.$zip.'<br />'.$phone.'<br />'.$email;

	$msg .= '<link href="'.JURI::root(true).'components/com_dtregister/assets/css/main.css" rel="stylesheet" type="text/css" /><table>';

	$msg .= '<h3>'.JText::_( 'DT_REGISTRATION_DETAILS' ).':</h3>';

	$msg .= '<table class="message">';

	$msg .= "<tr><td>".parse_tags($thanksmsg,$userId,$eventId)."</td></tr>";

	// $msg .= '<tr><td>'.JText::_( 'DT_NAME' ).': </td><td>'.$fname.' '.$lname.'</td></tr>';

	// $msg .= '<tr><td rowspan="2">'.JText::_( 'DT_ADDRESS' ).': </td><td>'.$address.'</td></tr>';

	// $msg .= '<tr><td>'.$city.' '.$state.' '.$zip.'</td><tr>';

	// $msg .= '<tr><td>'.JText::_( 'DT_AMOUNT' ).': </td><td>'.$currency_symbol. numberFormat($amount,2).'</td></tr><tr><td><h3>'.JText::_( 'DT_THANKS_PAYPAL' ).'</h3></td></tr>';

	echo  $msg.'<tr><td><a href="'. JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a></td></tr></table>';

	//Get custom fields and store in CustomFields array

	
}

// payment succeeded - update payment status

function paypal_complete($option){

	$userId=JRequest::getVar('user_id');

	$amount=JRequest::getVar('amount');

	$eventName=JRequest::getVar('eventId');

	$database = &JFactory::getDBO();

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	//Currency symbol

    $arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

			break;

	} else {

		$currency_symbol = NULL;

	}

	}

	$sql="Select * From #__dtregister_user where userId=$userId";

	$database->setQuery($sql);

	$rowUser = $database->loadObject();

	 //$amount= $_POST['mc_gross'];

	 $amount=$_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee'];

	 $address= $rowUser->userAddress;

	 $city = $rowUser->userCity;

	 $zip = $rowUser->userZip;

	 $state = $rowUser->userState;

	 $email = $rowUser->userEmail;

	 $country = $rowUser->userCountry;

	 $fname = $rowUser->userFirstName;

	 $lname = $rowUser->userLastName;

     $eventId = $rowUser->eventId;

    $sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	$eventName=$database->loadResult();

		$subthanksemail = sprintf($subthanksemail,$eventName);

		$thanksemail = sprintf($thanksemail,$eventName,$amountCharged);

	$msg .= '<link href="'.JURI::root(true).'/components/com_dtregister/assets/css/main.css" rel="stylesheet" type="text/css" />';

	$msg .=  '<h3>'.JText::_( 'DT_REGISTRATION_DETAILS' ).':PAY COMPLETE</h3>';

	$msg .= '<table class="message">';

	$msg.="<tr><td>".parse_tags($thanksmsg,$userId,$eventId)."</td></tr></table><br/>";

  $msg.= $fname . ' ' . JText::_( 'DT_ADMIN_MESSAGE' ) . ' ' . $eventName . '.<br /><br />';

	//$msg .= '<tr><td>'.JText::_( 'DT_NAME' ).': </td><td>'.$fname.' '.$lname.'</td></tr>';

	//$msg .= '<tr><td rowspan="2">'.JText::_( 'DT_ADDRESS' ).': </td><td>'.$address.'</td></tr>';

	//$msg .= '<tr><td>'.$city.' '.$state.' '.$zip.'</td><tr>';

	//$msg .= '<tr><td>'.JText::_( 'DT_AMOUNT' ).': </td><td>'.$currency_symbol. numberFormat($amount,2).'</td></tr></table><br/><h3>'.JText::_( 'DT_THANKS_PAYPAL' ).'</h3>';

	echo  $msg.'<a href="'. JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a>';

}

function processIdeal($option, $Itemid){

    global $Itemid , $mainframe;

	 $user = &JFactory::getUser();

	 $database = &JFactory::getDBO();

	 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	 $eventId = 	$_SESSION['register']['eventId'];

     $evt = new Event($eventId);

     $evt->over_ride_global();

	 $amount =		$_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee'] - $_SESSION['register']['discount_code_amount'];

	// $amount = 117 ;

	// $amount = $_POST['testamount'];

   $sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

   $database->setQuery($sql);

   $eventTitle=$database->loadResult();

   include(JPATH_SITE."/components/com_dtregister/ideal.class.php");

  /// echo JUri::root()."<br />";

   $return_url  = JUri::root().'index.php?option=com_dtregister&Itemid='.$Itemid.'&task=idealReturn&eventId='.$eventId; // 

   $report_url  = JUri::root().'index.php?option=com_dtregister&Itemid='.$Itemid.'&task=idealReport&eventId='.$eventId; // 

   $iDEAL = new iDEAL_Payment ($partner_id);

   if($idealmode=='test'){

     $iDEAL->setTestmode();

   }

   //$iDEAL->setTestmode();

   //echo $_POST['bank_id'] ;
  if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
    $paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
}else{
	$paid_amount = $_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee']-$_SESSION['register']['discount_code_amount'];
}
   
  $amount = round($paid_amount,2) ;
  
   $amount = $amount*100;
     $data = $iDEAL->createPayment($_POST['bank_id'], $amount, $eventTitle, $return_url, $report_url);

  // echo $data = $iDEAL->getBankURL();

  // var_dump($data);

  $mainframe->redirect( $iDEAL->getBankURL());

  if($amount < 118){

    echo JText::_( 'DT_ERROR_IDEAL_MINIMUM_AMOUNT' );

  }

}

function processEcheck($option, $Itemid){

	 global $Itemid;

	 $user = &JFactory::getUser();

	 $database = &JFactory::getDBO();

	 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	 $eventId = 	$_SESSION['register']['eventId'];

     $evt = new Event($eventId);

     $evt->over_ride_global();

	 $amount =		$_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee'] - $_SESSION['register']['discount_code_amount'];

	 $fname =		$database->getEscaped($_SESSION['register']['billingInfo']['firstname']);

	 $lname =		$database->getEscaped($_SESSION['register']['billingInfo']['lastname']);

	 $address =		$database->getEscaped($_SESSION['register']['billingInfo']['address']);

	 $city =		$database->getEscaped($_SESSION['register']['billingInfo']['city']);

	 $state =		$database->getEscaped($_SESSION['register']['billingInfo']['state']);

	 $zip =			$database->getEscaped($_SESSION['register']['billingInfo']['zip']);

	 $country =		$database->getEscaped($_SESSION['register']['billingInfo']['country']);

	 $phone =		$database->getEscaped($_SESSION['register']['billingInfo']['phone']);

	 $email =		$database->getEscaped($_SESSION['register']['billingInfo']['email']);

	 $org = 		$database->getEscaped($_SESSION['register']['billingInfo']['organization']);

	 $x_bank_acct_name = 	$database->getEscaped($_POST["x_bank_acct_name"]);

	 $x_bank_name = 		$database->getEscaped($_POST["x_bank_name"]);

	 $x_bank_acct_type = 	$database->getEscaped($_POST["x_bank_acct_type"]);

	 $x_bank_acct_num = 	$database->getEscaped($_POST["x_bank_acct_num"]);

	 $x_bank_aba_code = 	$database->getEscaped($_POST["x_bank_aba_code"]);

	 $userId=$user->id;

	 $savePaymentInfo=JRequest::getVar('ckb_save_info','','post');

	if(!isset($ses_invoiceno)){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$ses_invoiceno = "DC-".$x_invoice_num1;
		 $dt_user  = new DT_User();
         $ses_invoiceno = $dt_user->generateconfirmNum();

   	}

?>

<table border="0" cellpadding="3">

	<tr class="v">

		<td>

<?php

//Get the event title here
if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
    $paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
}else{
	$paid_amount = $_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee']-$_SESSION['register']['discount_code_amount'];
}
$amount = $paid_amount ;
$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

$database->setQuery($sql);

$eventTitle=$database->loadResult();

$auth_net_login_id			= $merchid;

$auth_net_tran_key			= $transkey;

$authnet_values				= array

(

	"x_login"				=> $auth_net_login_id,

	"x_version"				=> "3.1",

	"x_delim_char"			=> "|",

	"x_delim_data"			=> "TRUE",

	"x_type"				=> "AUTH_CAPTURE",

	"x_method"				=> "ECHECK",

 	"x_tran_key"			=> $auth_net_tran_key,

 	"x_relay_response"		=> "FALSE",

	"x_amount"				=> $amount,

//  ###########3  CUSTOMER DETAILS  ################3

	"x_first_name"			=>stripslashes(stripslashes($x_bank_acct_name)),

	"x_last_name"			=> "",

  	"x_company"    		 	=> stripslashes(stripslashes($org)),

	"x_address"				=> stripslashes(stripslashes(JRequest::getVar('billing_address','','post'))),

	"x_city"				=> JRequest::getVar('billing_city','','post'),

	"x_state"				=> JRequest::getVar('billing_state','','post'),

	"x_country"				=> $country,

	"x_phone"				=> $phone,

	"x_zip"					=> JRequest::getVar('billing_zipcode','','post'),

	"x_email"				=> JRequest::getVar('billing_email','','post'),

	"x_cust_id"				=>$x_invoice_num1,

//  ###########3  SHIPPING DETAILS  ################3

	"x_ship_to_first_name" 	=>stripslashes(stripslashes($fname)),

	"x_ship_to_last_name" 	=>stripslashes(stripslashes($lname)),

	"x_ship_to_address"  	=> stripslashes(stripslashes($address)),

	"x_ship_to_city" 		=>$city,

	"x_ship_to_state" 		=> $state,

	"x_ship_to_country" 	=> $country,

	"x_ship_to_zip" 		=> $zip,

	"x_ship_to_phone" 		=> $phone,

	"x_ship_to_email" 		=> $email,

	"x_ship_to_company" 			=> stripslashes(stripslashes($org)),

	"x_invoice_num" 		=> $ses_invoiceno,

	"x_bank_aba_code"		=> $x_bank_aba_code,

	"x_bank_acct_num"		=> $x_bank_acct_num,

	"x_bank_acct_type"		=> $x_bank_acct_type,

	"x_bank_name"			=> $x_bank_name,

	"x_bank_acct_name"		=> stripslashes(stripslashes($x_bank_acct_name)),

	"x_echeck_type"			=> "WEB",

	"x_recurring_billing"	=> "NO",

	"x_description"	=> $eventTitle

);

$fields = "";

//echo "<pre>";

//print_R($authnet_values);

foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";

if($echecknetmode == "test"){

	$ch = curl_init("https://test.authorize.net/gateway/transact.dll");

	} else {

	$ch = curl_init("https://secure.authorize.net/gateway/transact.dll");

	}

if($godaddy_hosting){

	curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

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

}

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_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###

$resp = curl_exec($ch); //execute post and get results

curl_close ($ch);

/*

RESPONSECODE  DESCRIPTION

1 This transaction has been approved.

2 This transaction has been declined.

3 There has been an error processing this transaction.

4 This transaction is being held for review.

*/

echo "<hr />";

$text = $resp;

$res = explode('|',$resp);

switch($res[0]){

case 1:

			echo "<b>".JText::_( 'DT_PAYMENT_SUCCESSFUL' )."</b><br />";

			echo 'Amount: ',$res[9],'<br />';

break;

case 2:

if($res[2]==2 || $res[2]==4){

echo "<b>".JText::_( 'DT_PAYMENT_DECLINED' )."</b>";

echo DT_REASON .": ",$res[3];

}

break;

case 3:

echo "<b>". JText::_( 'DT_ECHECK_PAYMENT_FAILED' ) ."</b><br />";

echo JText::_('DT_REASON') .": ",$res[3],'<br />';

break;

default:

echo "<b>".JText::_( 'DT_ERROR' )."</b><br />";

echo $res[3] . '<br />';

break;

echo "<hr />";

///////////////////////////////////////////////

}

?>

		</td>

	</tr>

</table>

<?php

	 //Encode the necessary information

	 //End of encode necessary information

	 if ($savePaymentInfo){

	 	global $ptc;

		$ptc->ToEncode=$x_bank_aba_code;

		$ptc->Encode();

		if($ptc->Encoded!=-1)

			$x_bank_aba_code=$ptc->Encoded;

		$ptc->ToEncode=$x_bank_acct_num;

		$ptc->Encode();

		if($ptc->Encoded!=-1)

		$x_bank_acct_num=$ptc->Encoded;

	 	$sql="Update #__comprofiler

	 			Set cb_routingnumber='$x_bank_aba_code',

	 			cb_acctnumber='$x_bank_acct_num',

	 			cb_bankname='$x_bank_name',

	 			cb_accountholder='$x_bank_acct_name'

	 			Where user_id=$userId

	 		";

	 	$database->setQuery($sql);

	 	$database->query();

	 }

/////////////////////////////////////////////////////////

echo "<hr />";

if($res[0]==1){

//if(1){

	$transactionid = $res[6];

	$transactionid = $ses_invoiceno ;

	// save the individual or group info
    $_SESSION['register']['billingInfo']['transaction_id'] = $transactionid ; 
	$user_id = saveInfo('E-Check (Authorize.net)', 1, $transactionid);

} else {

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$_SESSION['register']['billingInfo']['billing_address']=$billing_address;

		$_SESSION['register']['billingInfo']['billing_state']=$billing_state;

		$_SESSION['register']['billingInfo']['billing_city']= $billing_city;

		$_SESSION['register']['billingInfo']['billing_zipcode']=$billing_zipcode;

		$_SESSION['register']['billingInfo']['billing_email']=$billing_email

	//Failed transaction here

	//Add try again button form here

	//$user_id = saveInfo('E-Check (Authorize.net)', 0);

	?>

	<form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="eventId" value="<?php echo $eventId?>" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="payment" />

	<input type="hidden" name="type" value="echeck" />

		<input type="hidden" name="x_bank_acct_name" value="<?php echo $x_bank_acct_name?>" />

		<input type="hidden" name="x_bank_name" value="<?php echo $x_bank_name?>" />

		<input type="hidden" name="x_bank_acct_type" value="<?php echo $x_bank_acct_type?>" />

		<input type="hidden" name="x_bank_acct_num" value="<?php echo $x_bank_acct_num?>" />

		<input type="hidden" name="x_bank_aba_code" value="<?php echo $x_bank_aba_code?>" />

		<!-- Other field in bank account info-->

		<input type="submit" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>

	<?php

	}

	 if(isset($user_id) && $user_id > 0){

	  	$dt_user  =  new DT_User($user_id,$eventId);

	  	$dt_user->save_billing_info();

	  }

}

function processpayment($option, $Itemid){
    
	$user = &JFactory::getUser();
	$mosConfig_live_site = JURI::base( true );
    include("components/com_dtregister/config.dtregister.php");
   
	require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['paymentMethod'].'.php');
	
	$eventId = 	$_SESSION['register']['eventId'];

    $evt = new Event($eventId);

     $evt->over_ride_global();
	 $_SESSION['register']['billingInfo']['cardtype']=JRequest::getVar('cardtype','','post') ;

		$_SESSION['register']['billingInfo']['x_card_num']=JRequest::getVar('x_card_num','','post') ;									

		$_SESSION['register']['billingInfo']['x_exp_date']=JRequest::getVar('x_exp_date','','post') ;	

		$_SESSION['register']['billingInfo']['x_card_code']=JRequest::getVar('x_card_code','','post') ;	
		$billing_firstname=JRequest::getVar('billing_firstname','','post');

		$billing_lastname=JRequest::getVar('billing_lastname','','post');

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$_SESSION['register']['billingInfo']['billing_firstname']= $billing_firstname;

		$_SESSION['register']['billingInfo']['billing_lastname']=$billing_lastname;

		$_SESSION['register']['billingInfo']['billing_address']=$billing_address;

		$_SESSION['register']['billingInfo']['billing_state']=$billing_state;

		$_SESSION['register']['billingInfo']['billing_city']= $billing_city;

		$_SESSION['register']['billingInfo']['billing_zipcode']=$billing_zipcode;

		$_SESSION['register']['billingInfo']['billing_email']=$billing_email ;

	 $amountCharged=$_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee'] - $_SESSION['register']['discount_code_amount'];
	 $amount = $amountCharged;
    if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
		$paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
	}else{
		$paid_amount = $_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee']-$_SESSION['register']['discount_code_amount'];
	}
    $amount = $paid_amount ;	
	 
	 $payment =  new $_SESSION['register']['paymentMethod']();
				 $payment->setBillinginfo($_SESSION['register']['billingInfo']);
				 $payment->setPaymentType('registeration');
				 $payment->beforepayment();
				  $data =  array(
				        'eventName'=>  $evt->summary ,
						'amount'=>$amount ,
						'eventId'=>$eventId
				 );
				 $payment->setData($data);
				$status= $payment->processPayment();
				 
	 $_SESSION['register']['paymentMethod'] ;
	 
	 if($status){

		//Save information for future user

		$saveInformation=JRequest::getVar('ckb_save_info',0,'post');

		if ($saveInformation)

		{

			//Update #__comprofiler

			//Only save payment information

			$cartType=JRequest::getVar('cardtype','','post');

			$creditCardNumber=JRequest::getVar('x_card_num','','post');

			$expirationDate=JRequest::getVar('x_exp_date','','post');

			$cardCode=JRequest::getVar('x_card_code','','post');

			//Update code here to encode string

			global $ptc;

			$ptc->ToEncode=$creditCardNumber;

			$ptc->Encode();

			if($ptc->Encoded!=-1)

				$creditCardNumber=$ptc->Encoded;

			$ptc->ToEncode=$expirationDate;

			$ptc->Encode();

			if($ptc->Encoded!=-1)

				$expirationDate=$ptc->Encoded;

			$userId=$user->id;

			$sql="Update #__comprofiler

					Set cb_cardtype='$cardtype',

					cb_creditcardnumber='$creditCardNumber',

					cb_expdate='$expirationDate'

					Where user_id=$userId

					";

			$database->setQuery($sql);

			$database->query();

		}

		// save the individual or group info with payment verified

    if(isset($_SESSION['register']['billingInfo']['cardtype'])){

	   unset($_SESSION['register']['billingInfo']['cardtype']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_card_num'])){

	   unset($_SESSION['register']['billingInfo']['x_card_num']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_exp_date'])){

	   unset($_SESSION['register']['billingInfo']['x_exp_date']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_card_code'])){

	   unset($_SESSION['register']['billingInfo']['x_card_code']);

	}
    $_SESSION['register']['billingInfo']['transaction_id'] = $payment->TransactionID ; 
	 $user_id = saveInfo($_SESSION['register']['paymentMethod'],1,$payment->confirmNum);

		if(($res[0]==1)||($t=="TRUE")){
            $dt_event = new Event($eventId);
		  if($dt_event->thanksmsg_set){
				  $thanksmsg = $dt_event->thanksmsg;
			   }
	 		echo "<br />".stripslashes(parse_tags($thanksmsg,$user_id,$eventId ));

			echo "<hr />";

		}

   } else { 

		$_SESSION['register']['billingInfo']['cardtype']=$cardtype ;

		$_SESSION['register']['billingInfo']['x_card_num']=JRequest::getVar('x_card_num','','post') ;									

		$_SESSION['register']['billingInfo']['x_exp_date']=JRequest::getVar('x_exp_date','','post') ;	

		$_SESSION['register']['billingInfo']['x_card_code']=JRequest::getVar('x_card_code','','post') ;	

	echo $payment->tryagain();

   		// save the individual or group info with payment not verified

   		// $user_id = saveInfo('Credit Card (Authorize.net)',0,$ses_invoiceno);

   }
	 
}

// process the authorize.net form

function processAuthorizenet($option, $Itemid){

	$user = &JFactory::getUser();

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$eventId = 	$_SESSION['register']['eventId'];

    $evt = new Event($eventId);

     $evt->over_ride_global();

	$sql="Select summary From #__jevents_vevdetail Where evdet_id=$eventId";

	$database->setQuery($sql);

	 $event=$database->loadResult();

	$cardtype=JRequest::getVar("cardtype");

	$card_num=JRequest::getVar("x_card_num");

	$exp_date=JRequest::getVar("x_exp_date");

	$num=strlen($card_num);

	$cc_num="";

	$amountCharged=$_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee'] - $_SESSION['register']['discount_code_amount'];

	 //Update amountCharged here

	$sql="Select fe.field_id From #__dtregister_field_event as fe inner join #__dtregister_fields as df on fe.field_id=df.id where fe.event_id=$eventId and ((fe.showed=1) or (fe.showed =2 and df.showed=1))";

	$database->setQuery($sql);

	$rows=$database->loadObjectList();

	$arrFieldIds=array();

	for($i=0,$n=count($rows);$i<$n;$i++){

		$arrFieldIds[]=$rows[$i]->field_id;

	}

	if(count($arrFieldIds)){

		$sql="SELECT * FROM #__dtregister_fields WHERE id in (". implode(",",$arrFieldIds) .") AND fee_field=1 AND published=1 and hidden = 0 ORDER BY ordering ";

		$database->setQuery($sql);

		//echo $database->getQuery();

		if($database->getErrorMsg())

			echo $database->getErrorMsg();

		$rowCustoms=$database->loadObjectList();

	}else{

		$rowCustoms=null;

	}

	$amount = $amountCharged;
    if(isset($_SESSION['register']['billingInfo']['partial_payment'])){
		$paid_amount = $_SESSION['register']['billingInfo']['partial_payment'] ; 
	}else{
		$paid_amount = $_SESSION['register']['amountCharged']+$_SESSION['register']['billingInfo']['customFee']-$_SESSION['register']['discount_code_amount'];
	}
    $amount = $paid_amount ;
	$rowCustoms=null;

	for($i=0;$i<=$num-5;$i++){

		$cc_num.="x";

	}

	$cc_num.="-";

	$cc_num.=substr($card_num,$num-4,4);

  	$firstname	=$database->getEscaped($_SESSION['register']['billingInfo']['firstname']);

	$lastname	=$database->getEscaped($_SESSION['register']['billingInfo']['lastname']);

	$organization=$database->getEscaped($_SESSION['register']['billingInfo']['organization']);

	$address	=$database->getEscaped($_SESSION['register']['billingInfo']['address']);

	$city		=$database->getEscaped($_SESSION['register']['billingInfo']['city']);

	$state		=$database->getEscaped($_SESSION['register']['billingInfo']['state']);

	$zip		=$database->getEscaped($_SESSION['register']['billingInfo']['zip']);

	$country	=$database->getEscaped($_SESSION['register']['billingInfo']['country']);

	$phone		=$database->getEscaped($_SESSION['register']['billingInfo']['phone']);

	$email		=$database->getEscaped($_SESSION['register']['billingInfo']['email']);

	$memtot =$_SESSION['register']['memtot'];

	if(!isset($ses_invoiceno)){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$ses_invoiceno = "DC-".$x_invoice_num1;
		$dt_user  = new DT_User();
     $ses_invoiceno = $dt_user->generateconfirmNum() ;

   	}

$DEBUGGING					= 1;				# Display additional information to track down problems

$TESTING					= 0;				# Set the testing flag so that transactions are not live

$TESTING =($authnetmode=='test')?1:0;

$ERROR_RETRIES				= 2;				# Number of transactions to post if soft errors occur

$auth_net_url = ($authnetmode=='test')?"https://test.authorize.net/gateway/transact.dll":"https://secure.authorize.net/gateway/transact.dll" ;

$t= ($TESTING)?'TRUE':'FALSE';

$auth_net_login_id			= $merchid;

$auth_net_tran_key			= $transkey;

$authnet_values				= array

(

//  ###########3  MINIMUM TRANSACTION REQUIRED DETAILS  ################3

	"x_login"				=> $auth_net_login_id,

	"x_version"				=> "3.1",

    "x_delim_char"			=> "|",

	"x_delim_data"			=> "TRUE",

	"x_url"					=> "FALSE",

	"x_type"				=> "AUTH_CAPTURE",

	"x_method"				=> "CC",

 	"x_tran_key"			=> $auth_net_tran_key,

 	"x_relay_response"		=> "FALSE",

 	"x_test_request"		=> "FALSE",

	"x_card_num"			=> $card_num,

	"x_exp_date"			=> $exp_date,

	"x_description"			=> $event,

    "x_card_code"           =>JRequest::getVar("x_card_code"),

	"x_amount"				=>  $amount,

    "x_test_request"        => $t,

//  ###########3  CUSTOMER DETAILS  ################3

	"x_first_name"			=>JRequest::getVar('billing_firstname','','post'),

	"x_last_name"			=>JRequest::getVar('billing_lastname','','post'),

	"x_company"      		=>$organization,

	"x_address"				=>JRequest::getVar('billing_address','','post'),

	"x_city"				=>JRequest::getVar('billing_city','','post'),

	"x_state"				=>JRequest::getVar('billing_state','','post'),

	"x_phone"				=>$phone,

	"x_zip"					=>JRequest::getVar('billing_zipcode','','post'),

	"x_cust_id"				=>$x_invoice_num1,

	"x_email"				=>JRequest::getVar('billing_email','','post'),

//  ###########3  SHIPPING DETAILS  ################3

	"x_ship_to_first_name" 	=> $firstname,

	"x_ship_to_last_name" 	=> $lastname,

	 "x_ship_to_address"  	=> $address,

	"x_ship_to_city" 		=> $city,

	"x_ship_to_state" 		=> $state,

	"x_ship_to_country" 	=> $country,

	"x_ship_to_zip" 		=> $zip,

	"x_ship_to_phone" 		=> $phone,

	"x_ship_to_email" 		=> JRequest::getVar('billing_email','','post'),

//  ###########3  MERCHANT REQUIRED DETAILS  ################3

	"x_invoice_num" 		=> $ses_invoiceno,

	"cc_number" 			=> $cc_num,

	"cc_expdate" 			=> $exp_date,

	"cc_emailid" 			=> JRequest::getVar('billing_email','','post'),

);

$fields = "";

foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";

$ch = curl_init($auth_net_url); // URL of gateway for cURL to post to

// For GoDaddy hosting

$sql="SELECT config_value FROM  #__dtregister_config WHERE config_key='godaddy_hosting'";

$database->setQuery($sql);

$godaddy_hosting=$database->loadResult();

if($godaddy_hosting){

	curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

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

}

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_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###

$resp = curl_exec($ch); //execute post and get results

curl_close ($ch);

$res = explode('|',$resp);

if(($res[0]==1)||($t=="TRUE")){

	// echo "<br />".stripslashes($thanksmsg);

	//echo "<hr>";

}else{

	echo JText::_( 'DT_PAYMENT_DECLINED' );

	echo "<hr />";

	//echo $fields; // for debugging to know what is going to authorize.net

}

/*

RESPONSECODE  DESCRIPTION

1 This transaction has been approved.

2 This transaction has been declined.

3 There has been an error processing this transaction.

4 This transaction is being held for review.

*/

switch($res[0]){

	case 1:

		echo JText::_( 'DT_PAYMENT_SUCCESSFUL' ).'<br />';

		echo JText::_( 'DT_AUTHORIZATION_CODE' ).': '.$res[4].'<br />';

		echo JText::_( 'DT_AMOUNT' ).': '.$res[9].'<br />';

		echo JText::_( 'TRANS_ID' ).': '.$res[6].'<br />';

		echo JText::_( 'DT_INVOICE_NUMBER' ).': '.$res[7].'<br /><br />';

		break;

	case 2:

		if($res[2]==2 || $res[2]==4){

			echo JText::_( 'DT_PAYMENT_DECLINED' );

			echo JText::_( 'DT_REASON' ).": ",$res[3],'<br />';

		}

		break;

	case 3:

		/*

		echo "This transaction failed due to an error in application. Please notify the site administrator and provide the text that is displayed below:<br />";

		echo "Reason  :",$res[3],'<br />';

		*/

		if($TESTING){$status =1;

		}else{

			echo JText::_( 'DT_REASON' ).": ";

			switch($res[2]){

				case 5:

					echo JText::_( 'DT_AMOUNT_NOT_VALID' );

					break;

				case 6:

				case 37:

					echo JText::_( 'DT_CARD_NUMBER_INVALID' );

					break;

				case 7:

					echo JText::_( 'DT_EXP_DATE_INVALID' );

					break;

				case 11:

					echo JText::_( 'DT_DUPLICATE_TRANSACTION' );

					break;

				case 13:

					echo JText::_( 'DT_API_LOGIN_INVALID' );

					break;

				case 17:

				case 28:

					echo JText::_( 'DT_MERCHANT_NOT_CONFIGURED' );

					break;

				case 19:

				case 20:

				case 21:

				case 22:

				case 23:

				case 25:

				case 26:

				case 57:

				case 58:

				case 59:

				case 60:

				case 61:

				case 62:

				case 63:

					echo JText::_( 'DT_ERROR_OCCURRED' );

					echo '<a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'">'.JText::_( 'DT_CLICK_HERE' ).'</a>';

					break;

				case 27:

					echo JText::_( 'DT_AUTH_AVS_MISMATCH');

					break;

				case 34:

				case 35:

				case 38:

				case 43:

					echo JText::_( 'DT_AUTH_MERCH_SETUP_PROCESSOR' );

					break;

				case 49:

					echo JText::_( 'DT_AUTH_MAX_ALLOWED' );

					break;

				case 50:

					echo JText::_( 'DT_AUTH_TRANS_SETTLE_REFUNDED' );

					break;

				case 54:

					echo JText::_( 'DT_AUTH_REF_TRANS' );

					break;

				case 55:

					echo JText::_( 'DT_AUTH_SUM_CREDIT_REF_TRANS' );

					break;

				case 56:

					echo JText::_( 'DT_AUTH_ECHECK_ONLY' );

					break;

				case 66:

					echo JText::_( 'DT_AUTH_SECURITY_GUIDELINES' );

					break;

				case 68:

					echo JText::_( 'DT_AUTH_XVERSION_INVALID' );

					break;

				case 69:

					echo JText::_( 'DT_AUTH_XTYPE_INVALID' );

					break;

				case 78:

					echo JText::_( 'DT_AUTH_XCARD_FAILED' );

					break;

			}

		}

		break;

	}

	switch($res[38]){

		case 'N':

			echo JText::_( 'DT_AUTH_CC_CODE_MISMATCH' );

			break;

		case 'P':

			echo JText::_( 'DT_AUTH_CC_NOT_PROCESSED' );

			break;

		case 'S':

			echo JText::_( 'DT_AUTH_CC_CODE_NOT_PRESENT' );

			break;

		case 'U':

			echo JText::_( 'DT_AUTH_ISSUER_NOT_PROCESS' );

			break;

	}

	if(!$status)$status=$res[0];

	if($status==1){

		//Save information for future user

		$saveInformation=JRequest::getVar('ckb_save_info',0,'post');

		if ($saveInformation)

		{

			//Update #__comprofiler

			//Only save payment information

			$cartType=JRequest::getVar('cardtype','','post');

			$creditCardNumber=JRequest::getVar('x_card_num','','post');

			$expirationDate=JRequest::getVar('x_exp_date','','post');

			$cardCode=JRequest::getVar('x_card_code','','post');

			//Update code here to encode string

			global $ptc;

			$ptc->ToEncode=$creditCardNumber;

			$ptc->Encode();

			if($ptc->Encoded!=-1)

				$creditCardNumber=$ptc->Encoded;

			$ptc->ToEncode=$expirationDate;

			$ptc->Encode();

			if($ptc->Encoded!=-1)

				$expirationDate=$ptc->Encoded;

			$userId=$user->id;

			$sql="Update #__comprofiler

					Set cb_cardtype='$cardtype',

					cb_creditcardnumber='$creditCardNumber',

					cb_expdate='$expirationDate'

					Where user_id=$userId

					";

			$database->setQuery($sql);

			$database->query();

		}

		// save the individual or group info with payment verified

        if(isset($_SESSION['register']['billingInfo']['cardtype'])){

	   unset($_SESSION['register']['billingInfo']['cardtype']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_card_num'])){

	   unset($_SESSION['register']['billingInfo']['x_card_num']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_exp_date'])){

	   unset($_SESSION['register']['billingInfo']['x_exp_date']);

	}

	if(isset($_SESSION['register']['billingInfo']['x_card_code'])){

	   unset($_SESSION['register']['billingInfo']['x_card_code']);

	}
    $_SESSION['register']['billingInfo']['transaction_id'] = $res[6] ; 
	 $user_id = saveInfo('Credit Card (Authorize.net)',1,$ses_invoiceno);

		if(($res[0]==1)||($t=="TRUE")){
            $dt_event = new Event($eventId);
		  if($dt_event->thanksmsg_set){
				  $thanksmsg = $dt_event->thanksmsg;
			   }
	 		echo "<br />".stripslashes(parse_tags($thanksmsg,$user_id,$eventId ));

			echo "<hr />";

		}

   } else { 

		$billing_firstname=JRequest::getVar('billing_firstname','','post');

		$billing_lastname=JRequest::getVar('billing_lastname','','post');

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$_SESSION['register']['billingInfo']['billing_firstname']= $billing_firstname;

		$_SESSION['register']['billingInfo']['billing_lastname']=$billing_lastname;

		$_SESSION['register']['billingInfo']['billing_address']=$billing_address;

		$_SESSION['register']['billingInfo']['billing_state']=$billing_state;

		$_SESSION['register']['billingInfo']['billing_city']= $billing_city;

		$_SESSION['register']['billingInfo']['billing_zipcode']=$billing_zipcode;

		$_SESSION['register']['billingInfo']['billing_email']=$billing_email ;

		$_SESSION['register']['billingInfo']['cardtype']=$cardtype ;

		$_SESSION['register']['billingInfo']['x_card_num']=JRequest::getVar('x_card_num','','post') ;									

		$_SESSION['register']['billingInfo']['x_exp_date']=JRequest::getVar('x_exp_date','','post') ;	

		$_SESSION['register']['billingInfo']['x_card_code']=JRequest::getVar('x_card_code','','post') ;	

	?>

    <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="eventId" value="<?php echo $eventId?>" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="payment" />

	<input type="hidden" name="type" value="authorizenet" />

		<!-- Other field in bank account info-->

		<input type="submit" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>

    <?php

   		// save the individual or group info with payment not verified

   		// $user_id = saveInfo('Credit Card (Authorize.net)',0,$ses_invoiceno);

   }

      if(isset($user_id) && $user_id > 0){

	  	$dt_user  =  new DT_User($user_id,$eventId);

	  	$dt_user->save_billing_info();

	  }

}

function table_header($task, $type, $process=FALSE){

	global $option, $Itemid;

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( );
    if ($_SERVER['SERVER_PORT'] == 443){
	    $mosConfig_live_site = str_replace('http:','https:',$mosConfig_live_site);
	}
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	$eventId = $_SESSION['register']['eventId'];

	if(!isset($_SESSION['register']['eventId']) || $_SESSION['register']['eventId']==""){

		$eventId = $_REQUEST['eventId'];

	}

	$sql="SELECT evdet_id , summary,dtstart,dtend,noendtime FROM #__jevents_vevdetail WHERE evdet_id=$eventId";

	$database->setQuery($sql);

	$row = $database->loadObject();
     if(isset($row->noendtime) && $row->noendtime == 1){
			   $row->dtend = null ;
			}
	$eventName=$row->summary;

	$startDate=$row->dtstart;

	$endDate=$row->dtend;

	$sql="Select topmsg from #__dtregister_group_event where eventId={$eventId}";

	$database->setQuery($sql);

	$topmsg=$database->loadResult();

	if($task){$task = '&task=' . $task;}

	if($type){$type = '&type=' . $type;}

	if ($process == FALSE){
          
		$action = $mosConfig_live_site .'index.php?option=' . $option . '&eventId=' . $eventId . $task . $type . "&Itemid=" .  $Itemid;
		
		//$action = JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid. '&eventId=' . $eventId . $task ,$xhtml_url) ;

	} else if ($process == TRUE){

		$action = $mosConfig_live_site .'index.php?option=' . $option . '&eventId=' . $eventId . $task . $type . "&Itemid=" .  $Itemid;
		
		//$action = JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid. '&eventId=' . $eventId . $task ,$xhtml_url) ;

	}
    
	?>

	<div class="componentheading"><?php echo JText::_( 'DT_REGISTRATION' );?>:

		<?php

			$day1 = explode(" ",$row->dtstart);

			$day2 = explode(" ",$row->dtend);

			echo $eventName  ;

            if($event_show_date){

			echo ' ('.get_date($row->dtstart,$row->dtend,null,true);

			$start_date =JFactory::getDate($row->dtstart)->toFormat('%b %d, %Y');

			$end_date  = JFactory::getDate($row->dtend)->toFormat('%b %d, %Y');

			if($start_date == $end_date || $row->dtend==""){echo ')';} else {  echo ' - ' .get_date($row->dtend,null,true) . ')';}

           }
         
		?></div>

			<form name="frmcart" action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" >

	<?php

}

function list_registrants($option){

	global $mainframe , $Itemid;

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
    
	  $document	=& JFactory::getDocument();
    
    $document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.js');

	$document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.lightbox.js');

	$document->addStyleSheet(JURI::root(true).'/components/com_dtregister/assets/css/jquery.lightbox.css');
    
     if(isset($googlekey) && $googlekey !=""){

	  $document->addScript( "http://maps.google.com/maps?file=api".$amp."v=2.x".$amp."key=".$googlekey);

	}

   // $document->addScriptDeclaration("/*<![CDATA[*/ \n jQuery.noConflict(); \n /*]]>*/");

	$database = &JFactory::getDBO();
	$eventId = 	JRequest::getVar( 'eventId' );

	$evt = new Event($eventId);

	$show = $evt->get_field('show_registrant');

	if(!$show){

		echo JText::_( 'DT_EVENT_NOT_SHOWN');

		return ;

	}

	$fields = $evt->get_custom_fields_attendee_list();

	if(!$registrant_list){

		$my = &JFactory::getUser();

		if($my->id){

		}else{

			echo JText::_( 'DT_LOGIN_REQUIRED');

			return ;

		}

	}
   ?>
   <?php

           if($evt->location_id !="" && $showlocation==1){

		      $loc = new DTlocation($database);

			  $loc->load($evt->location_id);

			  if($loc->name !=""){

		 ?>

           <?php 
		    echo "<br /><strong>".JText::_( 'DT_LOCATION')  ; ?>:</strong>&nbsp;<a class="colorbox" href="<?php echo JRoute::_("index.php?option=com_dtregister&task=showlocation&location=".$evt->location_id."&no_html=1",$xhtml_url); ?>"   ><?php echo stripslashes($loc->name);?></a>

         <?php

		    if($linktogoogle==1){

		 ?>

         <?php

			}

			}

		   }

		 ?>
   
   <?php
	include_once( JPATH_SITE.'/includes/pageNavigation.php' );

	jimport('joomla.html.pagination');

	jimport('joomla.html.select');

	$listLimit = $mainframe->getCfg( 'list_limit', 10 );

	$order=JRequest::getVar( 'order' );

	$sort=JRequest::getVar( 'sort' );

	$limit=JRequest::getInt('limit',$listLimit);

	$limitstart  = JRequest::getVar('limitstart', 0, '', 'int');

	if (!$sort){$sort='asc';}

	if($sort=="asc"){

		$newsort ="desc";

		$sortImg = 'up' ;

	}else{

		$newsort ="asc";

		$sortImg = 'down' ;

	}

	$search  =JRequest::getVar( 'search' ,'' );

	if($search != ""){

		$where=" and  ( a.userFirstName like '%$search%' or  a.userLastName like '%$search%' )";

	}else {

		$where=" ";

	}

	$nameSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" " />';

   	$stateSortIcon  = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" "  />';

  	$dateSortIcon  = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0"  alt=" " />';

  	$citySortIcon  = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" " />';

   	$usernameSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" " />';

	$organizationSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" "  />';

	$addressSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" "  />';

	$zipSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" "  />';

	$countrySortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" " />';

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

	   ${$value->name.SortIcon} = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0"  alt=" " />' ; 

	}

	switch ($order) {

		case 'name':

			switch($registrant_name){

				case 1 :

					$orderBy = 'a.userFirstName '.$sort;

				break ;

				case 2 :

					$orderBy = 'a.userLastName '.$sort;

				break ;

				case 3 :

					$orderBy = 'a.userFirstName '.$sort.', a.userLastName '.$sort;

				break ;

			 }

			$nameSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		break;

		case 'date':

			$orderBy = 'a.register_date '.$sort;

			$dateSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" " />';

		break;

		case 'city':

			$orderBy = 'a.userCity '.$sort;

			$citySortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		break;

		case 'state':

			$orderBy = 'a.userState '.$sort;

			$stateSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		break;

		case 'username':

			$orderBy = 'u.username '.$sort;

			$usernameSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0"  alt=" " />';

		break;

		case 'address':

			$orderBy = 'a.userAddress '.$sort;

			$addressSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" " />';

		break;

		case 'organization':

			$orderBy = 'a.userOrganization '.$sort;

			$organizationSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		break;

		case 'zip':

			$orderBy = 'a.userZip '.$sort;

			$zipSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		break;

		case 'country':

			$orderBy = 'a.userCountry '.$sort;

			$countrySortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		break;

	    default :

		   $order_flag = true; 

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

		      if($order == $value->name){

			     $order_flag = false ;

				 $orderBy = 'a.'.$value->name.' '.$sort;

			     ${$value->name.'SortIcon'} = '<img alt=" " src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0"  />';

			  }

	       }

		  if($order_flag){

		    $orderBy = 'a.register_date '.$sort;

			$dateSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';

		  }

	}

	$paymentVerified = 0 ;

	if ($paymentVerified == 0){	$payVerified = ' AND ((payment_type <> "Authorize.net") || (a.pay_later_paid=0 and payment_type="Authorize.net"))';	} else { $payVerified = ' AND (a.pay_later_paid=1 and payment_type="Authorize.net")';}
	$paymentVerified = "";

	$listsql="SELECT  SQL_CALC_FOUND_ROWS  a.userId as  id, a.userCity , a.userState  ,a.userOrganization,a.userFirstName,a.userLastName,a.userEmail,a.userType,a.register_date,a.eventId,a.confirmNum,a.payment_type,a.pay_later_option,a.pay_later_paid,d.summary, d.dtstart , a.payment_verified, a.user_id , a.userCountry ,a.userAddress ,a.userZip , a.* , 

 e.numberOfPerson,e.amount,b.groupId,dis.code

  FROM

#__dtregister_user as a  inner join

#__dtregister_group as b on  a.userId= b.useid

inner join

#__jevents_vevdetail as d  on a.eventId=d.evdet_id

inner join

 #__dtregister_group_amount as e on b.groupId=e.groupId

left join #__dtregister_codes as dis on dis.id = a.discount_code_id

 " ;

 if($cb_integrated==1){

   $listsql .= " left join #__comprofiler as cb on cb.user_id = a.user_id left join  #__users as u on u.id = cb.user_id " ;

 }

$listsql .=" WHERE a.cancel <> 1 and   a.eventId=$eventId    $where    $payVerified ORDER BY $orderBy ";

$database->setQuery($listsql,$limitstart,$limit);

	$rowCounts=$database->loadObjectList();

	$database->setQuery('SELECT FOUND_ROWS();');

	$pageNav = new DtPagination( $database->loadResult(), $limitstart, $limit );

	$rows=$rowCounts ;

	echo "<p>".$registrant_message."</p>" ;

	?>

    <!--<script src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/jquery.js" language="javascript" type="text/javascript"></script>-->

    <script type="text/javascript">
     //<![CDATA[
	//jQuery.noConflict();

	DTjQuery(function(){

	  	DTjQuery('.detail').hide();

		DTjQuery('.userpar').click(function(){

			var path = new String(DTjQuery(this).children(':first').attr('src')) ; 

			if(path.match("expand") != null){

				DTjQuery(this).children(':first').attr('src',path.replace("expand","close"));

			}else{

				DTjQuery(this).children(':first').attr('src',path.replace("close","expand"));

			}

  			//DTjQuery(this).parent().next().toggle();
			cssdisplay = DTjQuery(this).parent().next().css('display');
			if(cssdisplay == null || (typeof(cssdisplay)!= undefined) && (cssdisplay.match("table-row") !=null || cssdisplay.match("block") !=null)){
			   DTjQuery(this).parent().next().css('display','none');
			}else{
			   DTjQuery(this).parent().next().css('display','table-row');
			}

		})

	})
     //]]>
	</script>
    <script type="text/javascript">
	  //<![CDATA[
     var map = null;

    var geocoder = null;

	var address = null;
    
	var display_address = null;
	
    function initialize() {

      if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById("map_canvas"));

        map.setCenter(new GLatLng(37.4419, -122.1419), 13);

        geocoder = new GClientGeocoder();

		showAddress(address);

      }

    }

    function showAddress(address) {

      if (geocoder) {

        geocoder.getLatLng(

          address,

          function(point) {

            if (!point) {

              alert(address + " not found");

            } else {

              map.setCenter(point, 13);

              var marker = new GMarker(point);

              map.addOverlay(marker);

              marker.openInfoWindowHtml(display_address);

            }

          }

        );

      }

    }

	DTjQuery(function(){ 

	  window.status='test';

	  DTjQuery(".colorbox").colorbox({width:550, height:550});

	  DTjQuery().bind('cbox_complete', function(){

		  initialize();

        //setTimeout($.fn.colorbox.next, 1500);

       });

	})
    //]]>
	</script>
  
    <table border="0" width="100%">

     <tr>

      <td align="left">

      <?php echo register_link($eventId);?>

      </td>

        <td align="right">

          <input type="text" name="search" value="<?php echo $search; ?>" />&nbsp;&nbsp;

          <input type="submit" name="search_submit" value="<?php echo  JText::_( 'DT_SEARCH'); ?>" />

          <input type="hidden" name="sort" value="<?php echo $sort?>" />

         <input type="hidden" name="order" value="<?php echo $order?>" />

        </td>

    </tr>

    </table>

    <br />

    <table border="0"  width="100%">

    <tr>

      <?php

        if($show_group_members == 1){

		?>

        	<th class="attendee_coltitle">&nbsp;</th>

        <?php

		}

	  ?>

    	<?php

		if($cb_integrated > 0 && $registrant_show_avatar ==1){

		?>

        	<th class="attendee_coltitle" >

        	<?php echo JText::_( 'DT_AVATAR')?>

        	</th>

        <?php

		}?>

    	<th class="attendee_coltitle" >

         <a href="#" onclick="document.frmcart.order.value='name'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_NAME')?>&nbsp;<?php echo isset($nameSortIcon)?$nameSortIcon:'';?>

        </a>

        </th>

         <?php

		if($registrant_username ==1 && $cb_integrated >0 ){

		?>

        	<th class="attendee_coltitle"  >

            <a href="#" onclick="document.frmcart.order.value='username'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_USERNAME')?>&nbsp;<?php echo isset($usernameSortIcon)?$usernameSortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

        <?php

		if($registrant_registered_date ==1){

		?>

        	<th class="attendee_coltitle"  >

             <a href="#" onclick="document.frmcart.order.value='date'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_DATE')?>&nbsp;<?php echo isset($dateSortIcon)?$dateSortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

		<?php

		if($registrant_organization ==1){

		?>

        	<th class="attendee_coltitle" >

            <a href="#" onclick="document.frmcart.order.value='organization'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_ORGANIZATION')?>&nbsp;<?php echo isset($organizationSortIcon)?$organizationSortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

          <?php

		if($registrant_address ==1){

		?>

        	<th class="attendee_coltitle" >

            <a href="#" onclick="document.frmcart.order.value='address'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_ADDRESS')?>&nbsp;<?php echo isset($addressSortIcon)?$addressSortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

		<?php

		if($registrant_city ==1){

		?>

        	<th class="attendee_coltitle" >

            <a href="#" onclick="document.frmcart.order.value='city'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_CITY')?>&nbsp;<?php echo isset($citySortIcon)?$citySortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

         <?php

		if($registrant_state ==1){

		?>

        	<th class="attendee_coltitle" >

            <a href="#" onclick="document.frmcart.order.value='state'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_STATE')?>&nbsp;<?php echo isset($stateSortIcon)?$stateSortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

          <?php

		if($registrant_zip ==1){

		?>

        	<th class="attendee_coltitle" >

            <a href="#" onclick="document.frmcart.order.value='zip'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_ZIPCODE')?>&nbsp;<?php echo isset($zipSortIcon)?$zipSortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

          <?php

		if($registrant_country ==1){

		?>

        	<th class="attendee_coltitle" >

            <a href="#" onclick="document.frmcart.order.value='country'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        	<?php echo JText::_( 'DT_COUNTRY')?>&nbsp;<?php echo isset($countrySortIcon)?$countrySortIcon:'';?>

            </a>

        	</th>

        <?php

		}?>

        <?php

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

		  $sort = isset(${$value->name.'SortIcon'})?${$value->name.'SortIcon'}:'';

		  $field_header .= '<th  class="attendee_coltitle" >

            <a  href="#" onclick="document.frmcart.order.value=\''.$value->name.'\'; document.frmcart.sort.value=\''.$newsort.'\'; document.frmcart.submit();return false;">

        	'.$value->label.'&nbsp;'.$sort.'

            </a>

        	</th>';

		}

		echo $field_header;

		?>

    </tr>

    <?php

    $k = 0 ;

	foreach($rows as $row){

		$user = new DT_User($row->id,$eventId);
         if($cb_integrated ==1){
		 $cb_user = $user->get_cb_user();
		}else if($cb_integrated ==2){
		  $cb_user = $user->get_jomsocial_user();
		}
		
		$members = $user->get_members();

		$html .="<tr class='eventListRow".($k+1).$class_show_member ." user".$row->id."'>";

		if( $show_group_members == 1){

            if($members){

				$class_show_member = " userpar ";

				$html .= '<td class="'.$class_show_member.'"><img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/expand.png" border="0" alt= " "/></td>';

			}else{

				$html .= '<td >&nbsp;</td>';

			}

		}

			$k = 1 - $k ;

			if($cb_integrated >0  && $registrant_show_avatar ==1){

				$html .='<td>';

				if($row->user_id > 0){

					if($cb_user->avatar != ""){

						if($registrant_cb_linked == 1){
                            JRoute::_('index.php?option=com_community&view=profile&userid='.$row->user_id.'&Itemid='.getcomItemId('com_community'));
							if($cb_integrated==2){
							   $html .= '<a  href="'.JRoute::_('index.php?option=com_community&view=profile&userid='.$row->user_id.'&Itemid='.getcomItemId('com_community'),$xhtml_url).'">';
							}else{
							  
							   $html .= '<a  href="'. JRoute::_('index.php?option=com_comprofiler&task=userProfile&user='.$row->user_id.'&Itemid='.getcomItemId('com_comprofiler'),$xhtml_url).'">';
							}
							
						}
                         if($cb_integrated==2){
						   
						   $html .= '<img src="'.JRoute::_('index.php?option=com_dtregister&task=thumb&filename='.$cb_user->avatar,$xhtml_url).'" border="0" alt= " " />';
						   
						 }else{
						  
						   $html .= '<img alt= " " src="'.JRoute::_('index.php?option=com_dtregister&task=thumb&filename=images/comprofiler/'.$cb_user->avatar,$xhtml_url).'" border="0" />';
						  
						 }
                          
						if($registrant_cb_linked == 1){

						$html .= '</a>';

						}

					}else{

						$html .='&nbsp;';

					}

				}else{

						$html .='&nbsp;';

				}

				$html .='</td>';

			}

			$html .= "<td>";

			if($registrant_cb_linked == 1 && $row->user_id > 0){
                if($cb_integrated==2){
				  
				   $html .= '<a  href="'.JRoute::_('index.php?option=com_community&view=profile&userid='.$row->user_id.'&Itemid='.getcomItemId('com_community'),$xhtml_url).'">';
				}else{
				   $html .= '<a  href="'.JRoute::_('index.php?option=com_comprofiler&task=userProfile&user='.$row->user_id.'&Itemid='.getcomItemId('com_comprofiler'),$xhtml_url).'">';
				}
				
			}

			switch($registrant_name){

				case 1:

					$html .=$row->userFirstName;

				break;

				case 2:

				$html .=$row->userLastName;

				break;

				case 3:

				$html .=$row->userFirstName.' '.$row->userLastName;

				break;

			}

		if($registrant_cb_linked == 1 && $row->user_id > 0){

				$html .= '</a>';

		}

		$html .= "</td>";

		if($registrant_username ==1 && $cb_integrated >0 ){

			$html .='<td>';

			if($registrant_cb_linked == 1 && $row->user_id > 0){
                
				 if($cb_integrated==2){
				   $html .= '<a  href="'.JRoute::_('index.php?option=com_community&view=profile&userid='.$row->user_id.'&Itemid='.getcomItemId('com_community'),$xhtml_url).'">';
				}else{
				   $html .= '<a  href="'.JRoute::_('index.php?option=com_comprofiler&task=userProfile&user='.$row->user_id.'&Itemid='.getcomItemId('com_comprofiler'),$xhtml_url).'">';
				}
				
			}

			$j_user = $user->get_joomla_user();

			if($j_user){

				$html .=$j_user->username;

			}else{

				$html .='&nbsp;';

			}

			if($registrant_cb_linked == 1 && $row->user_id > 0){

				$html .= '</a>';

			}

			$html .='</td>';

		}

		if($registrant_registered_date ==1 ){

			$html .='<td>'.get_date($row->register_date).'</td>';

		}

		if($registrant_organization ==1){

			$html .='<td>';

			$html .=$row->userOrganization;

			$html .='</td>';

		}

		if($registrant_address ==1){

			$html .='<td>';

			$html .=$row->userAddress;

			$html .='</td>';

		}

		if($registrant_city ==1){

			$html .='<td>';

			$html .=$row->userCity;

			$html .='</td>';

		}

		if($registrant_state ==1){

			$html .='<td>';

			$html .=$row->userState;

			$html .='</td>';

		}

    if($registrant_zip ==1){

			$html .='<td>';

			$html .=$row->userZip;

			$html .='</td>';

		}

		 if($registrant_country ==1){

			$html .='<td>';

			$html .=$row->userCountry;

			$html .='</td>';

		}

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

		  $html .='<td>';

		  $html .=$row->{$value->name};

		  $html .='</td>';

		}

		$html .= "</tr>";

		if($show_group_members == 1){

		    if($members){

				$html .='<tr class="detail member'.$row->id.'"><td colspan="9"><table border="0">';

				foreach($members as $member){

					$html .= "<tr>";

					$html .="<td width='100px;'>";

					$html .="&nbsp;</td>";

				  $html .="<td>";

					 switch($registrant_name){

							case 1:

								$html .=$member->firstname;

							break;

							case 2:

								$html .=$member->lastname;

							break;

							case 3:

								$html .=$member->firstname.' '.$member->lastname;

							break;

						}

					$html .= "</td>";

				   if($registrant_organization ==1){

			             $html .='<td>';

			             $html .=$member->organization;

			             $html .='</td>';

		             }

					if($registrant_address ==1){

						$html .='<td align="left" style="padding:0px 7px 0px 5px;">';

						$html .=$member->address;

						$html .='</td>';

					}

                   if($registrant_city ==1){

						$html .='<td align="left" style="padding:0px 7px 0px 5px;">';

						$html .=$member->city;

						$html .='</td>';

					}

					if($registrant_state ==1){

						$html .='<td align="left" style="padding:0px 7px 0px 5px;">';

						$html .=$member->state;

						$html .='</td>';

					}

					 if($registrant_zip ==1){

						$html .='<td>';

						$html .=$member->zip;

						$html .='</td>';

					}

					 if($registrant_country ==1){

						$html .='<td>';

						$html .=$member->country;

						$html .='</td>';

					}

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

					  $html .='<td>';

					  $html .=$member->{$value->name};

					  $html .='</td>';

					}

					$html .="</tr>";

				}

				$html .="</table></td></tr>";

			}

		}

	    unset($cb_user);

		unset($user);

		unset($j_user);

	}

	echo $html ;

	?>

    </table>

    <br />

    <table width="100%">

    <tr>

    <td colspan="4">

    <?php echo $pageNav->getListFooter(); // echo $pageNav->getPagesLinks(); ?>

      </td>

    </tr>

    <tr>

    <td>

    	<input type="hidden" name="option" value="<?php echo JRequest::getVar( 'option' ) ?>"  />

        <input type="hidden" name="eventId" value="<?php echo JRequest::getVar( 'eventId' ) ?>"  />

        <input type="hidden" name="task" value="<?php echo JRequest::getVar( 'task' ) ?>"  />

        <input type="hidden" name="Itemid" value="<?php echo $Itemid ?>"  />

    </td>

    </tr>

    </table>

    </form>

	<?php

}

function thumb($option){

	ob_clean();

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	include(JPATH_SITE."/components/com_dtregister/thumbnail.inc.php");

	$thumb = new Thumbnail($_GET['filename']);

     $registrant_avatar_width = JRequest::getVar('w', $registrant_avatar_width ) ;

	 $registrant_avatar_height = JRequest::getVar('h', $registrant_avatar_height ) ;

    $thumb->resize($registrant_avatar_width,$registrant_avatar_height);

   $thumb->show();

   exit;

}
function google_return($task){   
   
   	global $DT_mailfrom,$DT_fromname,$Itemid;

	$user = &JFactory::getUser();

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	
	$sql  = "select * from #__dtregister_session where id=".$_REQUEST['dtevent'];

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();
    
			 $data = unserialize($row[0]->data);
             $userId = $row[0]->user_id ;
			// if($userId ==  0 || $userId==""){
			 if(1){
			        if(isset($_SESSION['register']['billingInfo']['cardtype'])){

					   unset($_SESSION['register']['billingInfo']['cardtype']);
				
					}
				
					if(isset($_SESSION['register']['billingInfo']['x_card_num'])){
				
					   unset($_SESSION['register']['billingInfo']['x_card_num']);
				
					}
				
					if(isset($_SESSION['register']['billingInfo']['x_exp_date'])){
				
					   unset($_SESSION['register']['billingInfo']['x_exp_date']);
				
					}
				
					if(isset($_SESSION['register']['billingInfo']['x_card_code'])){
				
					   unset($_SESSION['register']['billingInfo']['x_card_code']);
				
					}
					require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['paymentMethod'].'.php');

                     $payment =  new $_SESSION['register']['paymentMethod']();

                     $payment->afterpayment();
					
					  $_SESSION['register']['billingInfo']['transaction_id'] = $payment->TransactionID ;
					 if($_SESSION['register']['paymentMethod'] !="GoogleCheckout"){
			      $userId = saveInfo($_SESSION['register']['paymentMethod'],1,$payment->confirmNum);
				 $sql = "update #__dtregister_session set user_id='".$userId."' where id=".$_REQUEST['dtevent'];
	 $database->setQuery($sql);
	  $database->query();
					 }
				 //die('user not saved');
			 }
    $currency_symbol=currency_symbol($currency_code);
	$dt_user = new DT_User($userId);
	 $dt_event = new Event($dt_user->eventId);
	 $dt_user->event = $dt_event ;
      if($dt_event->thanksmsg_set){
		      $thanksmsg = $dt_event->thanksmsg;
		   }
	 $rowUser = $dt_user ;
     $address= stripslashes($rowUser->userAddress);

	 $city = stripslashes($rowUser->userCity);

	 $zip = stripslashes($rowUser->userZip);

	 $state = stripslashes($rowUser->userState);

	 $email = stripslashes($rowUser->userEmail);

	 $country = stripslashes($rowUser->userCountry);

	 $fname = stripslashes($rowUser->userFirstName);

	 $lname = stripslashes($rowUser->userLastName);

	 $phone = stripslashes($rowUser->userPhone);

	 $org = stripslashes($rowUser->userOrganization);

	 $eventId = $rowUser->eventId;

	 $userType = $rowUser->userType;
	
	$msg .= '<link href="'.JURI::root(true).'components/com_dtregister/assets/css/main.css" rel="stylesheet" type="text/css" /><table>';

	$msg .= '<h3>'.JText::_( 'DT_REGISTRATION_DETAILS' ).':</h3>';

	$msg .= '<table class="message">';

	$msg .= "<tr><td colspan=2>".parse_tags($thanksmsg,$userId,$dt_user->eventId)."</td></tr>";

	$msg .= '<tr><td>'.JText::_( 'DT_NAME' ).': </td><td>'.$fname.' '.$lname.'</td></tr>';

	$msg .= '<tr><td rowspan="2">'.JText::_( 'DT_ADDRESS' ).': </td><td>'.$address.'</td></tr>';

	$msg .= '<tr><td>'.$city.' '.$state.' '.$zip.'</td><tr>';

	$msg .= '<tr><td>'.JText::_( 'DT_AMOUNT' ).': </td><td>'.$currency_symbol. numberFormat($dt_user->get_amount(),2).'</td></tr>';

	echo  $msg.'<tr><td><a href="'.JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a></td></tr></table>';
   
}
function ideal_return($option){

   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

   	 $eventId = 	$_SESSION['register']['eventId'];

     $evt = new Event($_GET['eventId']);

     $evt->over_ride_global();

   include(JPATH_SITE."/components/com_dtregister/ideal.class.php");

   global $mainframe , $Itemid;

   $mosConfig_live_site = JURI::base( true );

    if (isset($_GET['transaction_id'])) {  

    $iDEAL = new iDEAL_Payment ($partner_id);

    $iDEAL->checkPayment($_GET['transaction_id']);

    if ($iDEAL->getPaidStatus() == true) {
          $_SESSION['register']['billingInfo']['transaction_id'] = $_GET['transaction_id'] ;
      saveInfo('ideal',1);

    }else{

	 $msg .= '<strong>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</strong>';

	echo $msg.'<p><a href="'.JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a></p></form>';

	}

  }

}

function ideal_report($option){

   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

   	 $eventId = 	$_SESSION['register']['eventId'];

     $evt = new Event($_GET['eventId']);

     $evt->over_ride_global();

   global $mainframe , $Itemid;

   echo JText::_( 'DT_ERROR_PAYMENT_IDEAL' );

   echo "</form>";

}

function showlocation($option){

   global $mainframe ;
   ob_clean();
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

   $id = JRequest::getVar('location', '' ) ;

   $location =  new DTlocation();

   $location->load($id);

   include(JPATH_SITE."/components/com_dtregister/view/location/view.php");
   
   die ;

}
function history($option){
    
	global $Itemid  , $mainframe;
	include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	unset($_SESSION['billinginfo']['register']['user']);
	unset($_SESSION['billinginfo']['register']['feechanges']);
	unset($_SESSION['register']);
	$user	 =& JFactory::getUser();
	if ($user->get('id') == 0) {
			$url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);
			return;
    }
	include_once( JPATH_SITE.'/includes/pageNavigation.php' );
	jimport('joomla.html.pagination');

	jimport('joomla.html.select');

	$listLimit = $mainframe->getCfg( 'list_limit', 10 );

	$database = &JFactory::getDBO();
	$order=JRequest::getVar( 'order' );

	$sort=JRequest::getVar( 'sort' );
	$limit=JRequest::getInt('limit',$listLimit);
	$limitstart  = JRequest::getVar('limitstart', 0, '', 'int');
	
	if (!$sort){$sort='desc';}
	if($sort=="asc"){

		$newsort ="desc";

		$sortImg = 'up' ;

	}else{
		$newsort ="asc";
		$sortImg = 'down' ;
	}
	$search  =JRequest::getVar( 'search' ,'' );
	if($search != ""){

		$con_search =" and  ( je.summary like '%$search%' )";

	}else {

		$con_search=" ";

	}
	$nameSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" "  />';
	$amountSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0"  alt=" " />';
	$amountDueSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" "  />';
	$payment_verifiedSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0"  alt=" " />';
	$payment_verifiedSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" " />';
	$cancelSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/up.png" border="0" alt=" " />';
	
	switch ($order) {
	   
	   case 'summary':
	      $orderBy = 'je.summary '.$sort;
	      $nameSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';
	   break ;
	   case 'amount':
	      $orderBy = 'a.amount '.$sort;
	      $amountSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" " />';
	   break ;
	   case 'amount_due':
	      $orderBy = 'u.due_payment '.$sort;
	      $amountDueSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0"  />';
	   break ;
	   case 'register_date':
	      $orderBy = 'u.register_date '.$sort;
	      $register_dateSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';
	   break ;
	   case 'register_date':
	      $orderBy = 'u.payment_verified '.$sort;
	      $payment_verifiedSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';
	   break ;
	    case 'cancel':
	      $orderBy = 'u.cancel '.$sort;
	      $cancelSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';
	   break ;
	   default :
	    
		  $orderBy = 'u.register_date '.$sort;
	      $register_dateSortIcon = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/'.$sortImg.'.png" border="0" alt=" "  />';
	   
	}
	$paymentVerified = JRequest::getVar('paymentVerified',''); ;

	if ($paymentVerified != ""){	$payVerified = ' AND u.pay_later_paid='.$paymentVerified;	} else { $payVerified = '';}

	$dt_user = new DT_User();
	$recs = $dt_user->find(" u.user_id =".$user->get('id')." $con_search "." $payVerified ",$orderBy,$limitstart, $limit );
	$database->setQuery('SELECT FOUND_ROWS();');
    $rowcount =  $database->loadResult() ;
	$pageNav = new DtPagination( $rowcount, $limitstart, $limit );
	unset($dt_user);
	 $arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

				break;

			} else {
	
				$currency_symbol = NULL;
	
			}

		}
	   
		$k=0;
	$html = '<tr>
	              <td colspan="7">
				   '.JText::_('DT_NO_REG_RECORDS').'
				  </td>
	            </tr>';
	if(count($recs)>0){
	   $html = "" ;
	}
	foreach($recs as $key=>$rec){
	  
	   $dt_user = new DT_User($rec->userId,$rec->eventId);
	   
	  $edit = "";
	  
	  if($dt_user->is_editable()){
	     //$edit = JHtml::link("index.php?option=com_dtregister&task=dtregedit&id=".$rec->userId."&Itemid=".$Itemid,JText::_( 'DT_EDIT_DETAILS'));
		 $edit = JHtml::link(JRoute::_("index.php?option=com_dtregister&task=dtregedit&id=".$rec->userId."&Itemid=".$Itemid,$xhtml_url),'<img border="0"  src="'.JURI::root(true).'/images/M_images/edit.png" alt="'.JText::_( 'DT_EDIT').'" />');
	  }else{
	     $edit = "";
	  }
	  // echo "<pre>";
    // print_r($rec);
	  // echo "</pre>";
	  $dt_user->event->resume_global();
	  $dt_user->event->over_ride_global();
	  
	  $currency_symbol = currency_symbol($currency_code);
	  if($currency_symbol==""){
	     $dis_currency_code = $currency_code ;
	  }else{
	    $dis_currency_code = "" ;
	  }
	  $amount =  $currency_symbol. numberFormat($rec->amount,2)." ".$dis_currency_code;
    $due =  $currency_symbol. numberFormat(($rec->amount - $rec->paid_amount),2)." ".$dis_currency_code;
	  if(($rec->amount - $rec->paid_amount) > 0  && $rec->cancel!=1){ // && $rec->pay_later_paid==0
	  
	     if($dt_user->is_payable()){
		    $payment = JHtml::link(JRoute::_("index.php?option=com_dtregister&task=confirmpay&id=".$rec->userId."&Itemid=".$Itemid,$xhtml_url) ,JText::_( 'DT_MAKE_PAYMENT'));
		 }else{
		    $payment = "" ;
		 }
	     
	  }else{
	     if($rec->cancel == 1 && $rec->due_payment < 0){
		      $due = $currency_symbol.numberFormat($rec->due_payment,2)." ".$dis_currency_code;
		 }else{
		     $due = $currency_symbol.numberFormat(0,2)." ".$dis_currency_code;
		 }
	     $payment =  JText::_( 'DT_PAID') ; 
		
	  }
	  if($k == 0){$bgRow='eventListRow1';}else{$bgRow='eventListRow2';}
	  
	  if($dt_user->is_cancelabelable()){
	    $link = '<img border="0"  src="'.JURI::root(true).'/components/com_dtregister/assets/images/publish_x.png" alt="'.JText::_( 'DT_CANCEL').'" />';
		
	    $cancel_link = '<a href="'. JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=cancel&id='.$dt_user->id,$xhtml_url ).'" >'.$link .'
</a>';
	  }else{
	     $cancel_link = "&nbsp;";
	  }
	  
	  /*
	   elseif($dt_user->cancel==1){
	     $cancel_link = JText::_( 'DT_CANCELLED');  
	  }
	  */
	  $status = array(JText::_( 'DT_ACTIVE'),JText::_( 'DT_CANCELLED'),JText::_( 'DT_PENDING'));
	   $html .= '<tr class="'.$bgRow.'">
	              <td>'.tmpl_event_name($event_show_date,$rec->summary,get_date_only($rec->dtstart,$rec->dtend)).' </td>
				  <td align="center">'.$edit.'</td>
				  <td align="right">'.$amount.'</td>
				  <td align="right" >'.$due.'</td><td align="center">'.get_date($rec->register_date).'</td>
				  <td align="center">'.$payment.'</td>
				  <td align="center">'.$cancel_link.'</td>
				  
				  <td align="center">'.$status[$rec->cancel].'</td>
				  
	            </tr>';
	 
	  unset($dt_user);
	  $k = 1 - $k;
	   
	}
	 
	?>
    
    <form name="frmcart" action="<?php    echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=history',$xhtml_url ) ; 	?>" method="post" >
    <table border="0" width="100%">
     <tr>
       <td colspan="2">
         <?php echo $userpanelmessage; ?>
       </td>
     </tr>
     <tr>
      <td align="left">
       <?php 
	     $options[]=JHTML::_('select.option',"",JText::_( 'DT_SELECT_PAYMENT_STATUS'));
	     $options[]=JHTML::_('select.option',1,JText::_( 'DT_PAID'));
		   $options[]=JHTML::_('select.option',0,JText::_( 'DT_NOT_PAID'));
		   echo JHTML::_('select.genericlist',$options,"paymentVerified","class=\"evt_new\" onchange='document.frmcart.submit();'","value","text",$paymentVerified);
	     ?>
      </td>
      <td align="right">
         <input type="text" name="search" value="<?php echo $search; ?>" />&nbsp;&nbsp;
         <input type="submit" name="search_submit" value="<?php echo  JText::_( 'DT_SEARCH'); ?>" />
         <input type="hidden" name="sort" value="<?php echo $sort?>" />
         <input type="hidden" name="order" value="<?php echo $order?>" />
      </td>
    </tr>
    </table>
    <br />
    <table>
     <tr>
      <th>
        <a href="#" onclick="document.frmcart.order.value='summary'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_EVENT')?>&nbsp;<?php echo isset($nameSortIcon)?$nameSortIcon:'';?>

        </a>
      </th>
       <th><center><u><?php echo JText::_( 'DT_EDIT')?></u></center></th>
      <th>
           <a href="#" onclick="document.frmcart.order.value='amount'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_AMOUNT')?>&nbsp;<?php echo isset($amountSortIcon)?$amountSortIcon:'';?>

        </a>
      </th>
      <th>
          <a href="#" onclick="document.frmcart.order.value='amount_due'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_AMOUNT_DUE')?>&nbsp;<?php echo isset($amountDueSortIcon)?$amountDueSortIcon:'';?>

        </a>
      </th>
      <th>
          <a href="#" onclick="document.frmcart.order.value='register_date'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_REGISTRATION')." ".JText::_( 'DT_DATE') ?>&nbsp;<?php echo isset($register_dateSortIcon)?$register_dateSortIcon:'';?>

        </a>
      </th>
      <th>
         <a href="#" onclick="document.frmcart.order.value='payment_verified'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_PAYMENTS'); ?>&nbsp;<?php echo isset($payment_verifiedSortIcon)?$payment_verifiedSortIcon:'';?>

        </a>
      </th>
      
      <th>
         
        <u><?php echo JText::_( 'DT_CANCEL'); ?></u>
        
      </th>
      
      <th>

        <a href="#" onclick="document.frmcart.order.value='cancel'; document.frmcart.sort.value='<?php echo $newsort?>'; document.frmcart.submit();return false;">

        <?php echo JText::_( 'DT_STATUS'); ?>&nbsp;<?php echo isset($cancelSortIcon)?$cancelSortIcon:'';?>

        </a>
      </th>

     </tr>
     <?php echo $html ; ?>
    </table>
     <table width="100%">

    <tr>
    <td colspan="4">
    <?php echo $pageNav->getListFooter(); ?>
      </td>
    </tr>
    <tr>
    <td>
    	  <input type="hidden" name="option" value="<?php echo JRequest::getVar( 'option' ) ?>"  />
        <input type="hidden" name="task" value="<?php echo JRequest::getVar( 'task' ) ?>"  />
        <input type="hidden" name="Itemid" value="<?php echo $Itemid ?>"  />
    </td>
    </tr>
    </table>
    </form>
    <?php 
	unset($_SESSION['billinginfo']['register']);
}
function editUser($option){   
   
   global $Itemid , $mainframe ,$now;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $user	 =& JFactory::getUser();
   if ($user->get('id') == 0) {
	 $url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);
	  return;
   }
   $id=JRequest::getVar( 'id' );
   $dt_user =  new DT_User($id);
   if(!isset($_SESSION['billinginfo']['register']['user'])){
      $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;
   }
   
   if(!isset($_SESSION['billinginfo']['register']['members']) || count($_SESSION['billinginfo']['register']['members']) < 1 ){
     $members = $dt_user->get_members();
	 $_SESSION['billinginfo']['register']['members'] = $members;
	 
	 $members = $_SESSION['billinginfo']['register']['members'] ;
	 
   }else{ 
     $members = $_SESSION['billinginfo']['register']['members'] ;
   }
   $memchgdone=JRequest::getVar( 'memchgdone' );
  if(count($dt_user->get_members()) > 0 && $memchgdone == ""){
	 // header("Location:index.php?option=com_dtregister&task=listmembers&Itemid=".$Itemid."&id=".$id);
	  //exit ;
	
	}
   if($dt_user->is_editable()){
      
   }else{
     $url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);
	  return ;
   }
     $eventId = $dt_user->eventId;

    $sql="Select use_discountcode from #__dtregister_group_event where eventId=$eventId limit 0,1";

    $database->setQuery($sql);
    $use_discountcode=$database->loadResult();
    $dt_code = new DiscountCode($row->discount_code_id);
    $discount_code = $dt_code->code;

    $field_used = ($dt_user->get_amount()>0)?'p':'f';
	$my = &JFactory::getUser();
    if($cb_integrated > 0 && $cbviewonly==1 && $my->id){
        $fields_readyonly = ' readonly="readonly" ';
	    $dropdown_disable = " disabled ";
    }
	?>
  <link rel="stylesheet" href="<?php echo JURI::root(true) ?>/media/system/css/calendar-jos.css" type="text/css"  title="green"  media="all" />
  <script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/mootools.js"></script>
 
  <script src="<?php echo JURI::root(true); ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>
   <script src="<?php echo JURI::root(true); ?>/components/com_dtregister/assets/js/textareaCounter.js" type="text/javascript"></script>
  <script language="JavaScript" type="text/javascript">
    //<![CDATA[
   // jQuery.noConflict();
	//]]>
  </script>
<script language="JavaScript" type="text/javascript">
    //<![CDATA[
	//window.addEvent('domready', function(){ var JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false}); });
  //]]>
  </script>
<?php

$evt = new Event($eventId);
$evt->read();
?>

<!-- Begin User Panel Edit Record Form -->

<div class="componentheading"><?php echo JText::_( 'DT_EDIT_RECORD' );?>: <?php echo $evt->summary; ?></div>
     <form name="frmcart" method="post" action="index.php?Itemid=<?php echo $Itemid ; ?>" enctype="multipart/form-data">
      <table cellpadding="4" cellspacing="1" border="0" width="100%" class="">
      <tr>
      <td colspan="2"><table>
      <?php
	  if(count($dt_user->get_members())>0){
	   
	  ?>
         
        <td><a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=listmembers&id='.$id,$xhtml_url ) ; ?>"><?php echo  JText::_( 'DT_EDIT_MEMBERS' ); ?></a></td>
     
      <?php
	  }else{
	    ?>
         <td>&nbsp;</td>
        <?php
	  }
	  ?>
      <?php
	  if($evt->cancel_date ==""){
	     $now->toFormat('%Y-%m-%d') ;
	     $evt->cancel_date = strtotime($now->toFormat('%Y-%m-%d')." +1 day");
	  }else{
	     $evt->cancel_date = strtotime($evt->cancel_date);
	  }
      if($front_link_type==1){
	      $link = '<img src="'.JURI::root(true).'/components/com_dtregister/assets/images/'.$button_color.'/cancel_230.png" border="0"  />' ;
	  }else{
	     $link = "[".JText::_( 'DT_CANCEL_REGISTRATION' )."]" ;
	  }
	  ?>
      <!--td>
          
          <?php
          if($evt->cancel_date > $now->toUnix(true) && $evt->cancelfee_enable ==1){
		     
		  ?>
          
          <a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=cancel&id='.$id,$xhtml_url ); ?>"><?php echo $link; ?>
</a>
 <?php
   }
 ?>

</td -->
      </td>
       </table></td>
       
       </tr>
      <tr><td class="fieldlabel"><?php echo JText::_( 'DT_EVENT' ); ?>:</td><td><strong><?php echo $evt->summary;?></strong></td><td width="2%" >&nbsp;</td></tr>

	   <tr><td class="fieldlabel"><?php echo JText::_( 'DT_CONFIRMATION_NUMBER' ); ?>:</td><td><?php echo $dt_user->confirmNum;?></td><td width="2%" >&nbsp;</td></tr>

<?php //if($discount_code !=""){ 
   
   if($dt_user->transaction_id != ""){ 
?>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_TRANSACTION_ID' ); ?>:</td><td><?php echo  $dt_user->transaction_id; ?></td><td width="2%" >&nbsp;</td></tr>

<?php } 

?>

<?php //if($discount_code !=""){ 
   
   if(1){ 
?>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_DISCOUNT_CODE' ); ?>:</td><td><?php echo $discount_code; ?></td><td width="2%" >&nbsp;</td></tr>

<?php } 

?>

<?php

if(${$field_used._s_title}){?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_TITLE' ); ?>:
<?php if(${$field_used._r_title}){ ?>

				<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

			<?php } 
			 $titles = explode("|",$titleoptions);
	$temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

	foreach($titles as $title){
	
		$temp[] = JHTML::_('select.option', $title, $title);
	
	}
	        
	$titles = $temp;
			
			?>
</td><td><?php echo  JHTML::_('select.genericlist',$temp,'title', 'class="inputbox" size="1"', 'value', 'text',$dt_user->userTitle); ?></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_FIRSTNAME' ); ?>:<span class="required">&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input class="inputbox" type="text" name="firstname" value="<?php echo stripslashes($dt_user->userFirstName);?>" <?php echo ($dt_user->userFirstName!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_LASTNAME' ); ?>:<span class="required">&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input class="inputbox" type="text" name="lastname" value="<?php echo stripslashes($dt_user->userLastName);?>" <?php echo ($dt_user->userLastName!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php

if(${$field_used._s_organization}){?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ORGANIZATION' ); ?>:
<?php if(${$field_used._r_organization}){ ?>

				<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

			<?php } ?>
</td><td><input class="inputbox"  type="text" name="organization" value="<?php echo stripslashes($dt_user->userOrganization);?>"  <?php echo ($dt_user->userOrganization!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if(${$field_used._s_address}){?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS' ); ?>:
	<?php if(${$field_used._r_address}) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>
</td><td><input type="text" class="inputbox"  name="address" value="<?php echo stripslashes($dt_user->userAddress);?>" <?php echo ($dt_user->userAddress!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>

<?php if(${$field_used._s_address2}){?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS2' ); ?>:
	<?php if(${$field_used._r_address2}) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>
</td><td><input type="text" class="inputbox"  name="address2" value="<?php echo stripslashes($dt_user->userAddress2);?>" <?php echo ($dt_user->userAddress2!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>

<?php if(${$field_used._s_city}){?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_CITY' ); ?>:
<?php if(${$field_used._r_city}) { ?>

			<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span>

		<?php } ?>
</td><td><input type="text" class="inputbox"  name="city" value="<?php echo stripslashes($dt_user->userCity);?>" <?php echo ($dt_user->userCity!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if(${$field_used._s_state}){ ?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_STATE' ); ?>:
<?php if(${$field_used._r_state}){ ?> <span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>
</td><td><input type="text" class="inputbox"  name="state" value="<?php echo stripslashes($dt_user->userState);?>" <?php echo ($dt_user->userState!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if(${$field_used._s_country}){ require("components/com_dtregister/country.htm"); } ?>
<?php if(${$field_used._s_zip}){ ?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ZIPCODE' ); ?>:
 <?php if(${$field_used._r_zip}){ ?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

</td><td><input type="text" class="inputbox"  name="zip" value="<?php echo stripslashes($dt_user->userZip);?>" <?php echo ($dt_user->userZip!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if(${$field_used._s_phone}){ ?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_PHONE' ); ?>:
<?php if(${$field_used._r_phone}) { ?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php } ?>

</td><td><input type="text" class="inputbox"  name="phone" value="<?php echo stripslashes($dt_user->userPhone);?>" <?php echo ($dt_user->userPhone!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_EMAIL' ); ?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox"  name="email" value="<?php echo stripslashes($dt_user->userEmail);?>" <?php echo ($dt_user->userEmail!="")?$fields_readyonly:''; ?> /></td><td width="2%" >&nbsp;</td></tr>
<?php

//var_dump($dt_user);
if($dt_user->userType=='G'){
 $field_type = "B";
}else{
  $field_type = "I";
}
echo $evt->field_html($field_type,$dt_user);

?>
<script type="text/javascript">
//<![CDATA[
function validation(){

  <?php if(${$field_used._s_title} && ${$field_used._r_title}){ ?>

			if(document.frmcart.title.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_TITLE' ); ?>");

				document.frmcart.title.focus();

				return;

			}

		<?php }
		?>
if(document.frmcart.firstname.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_FNAME' ); ?>");

				document.frmcart.firstname.focus();

				return ;

		}

		if(document.frmcart.lastname.value==""){

					alert ("<?php echo JText::_( 'DT_ENTER_LNAME' ); ?>");

					document.frmcart.lastname.focus();

					return;

		}

		<?php if(${$field_used._s_organization} && ${$field_used._r_organization}){ ?>

			if(document.frmcart.organization.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ORGANIZATION' ); ?>");

				document.frmcart.organization.focus();

				return;

			}

		<?php }

		if(${$field_used._s_address} && ${$field_used._r_address}){?>

			if(document.frmcart.address.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS' ); ?>");

				document.frmcart.address.focus();

				return;

			}

		<?php }
?>
  <?php if(${$field_used._s_address2} && ${$field_used._r_address2}){ ?>

			if(document.frmcart.address2.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS2' ); ?>");

				document.frmcart.address2.focus();

				return;

			}

		<?php }
		?>
<?php

		if(${$field_used._s_city} && ${$field_used._r_city}){ ?>

			if(document.frmcart.city.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_CITY' ); ?>");

	    	document.frmcart.city.focus();

			return;

			}

		<?php }

		if(${$field_used._s_state} && ${$field_used._r_state}){ ?>

			if(document.frmcart.state.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_STATE' ); ?>");

			document.frmcart.state.focus();

			return;

			}

		<?php }

		if(${$field_used._s_zip} && ${$field_used._r_zip}){ ?>

			if(document.frmcart.zip.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ZIP' ); ?>")

			document.frmcart.zip.focus();

			return false;

			}

		<?php } ?>

		if(document.frmcart.email.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

			document.frmcart.email.focus();

			return;

		}

		if(document.frmcart.email.value!=""){

			var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

			var returnval=emailfilter.test(document.frmcart.email.value)

			if (returnval==false){

				alert("<?php echo JText::_( 'DT_INVALID_EMAIL' ); ?>");

				document.frmcart.email.select();

				document.frmcart.email.focus();

				return ;

			}

		}

		<?php if(${$field_used._s_phone} && ${$field_used._r_phone}){ ?>

				if(document.frmcart.phone.value==""){

					alert("<?php echo JText::_( 'DT_ENTER_PHONE' ); ?>");

					document.frmcart.phone.focus();

					return;

				}

		<?php }

echo $evt->javavalidation ;
?>
document.frmcart.submit();
}
//]]>
</script>
<tr><td colspan="3" align="center"><input type="button" class="button" value="<?php echo JText::_( 'DT_BACK' ); ?>" onclick="javascript:history.back();" />&nbsp;<input type="button" name="saveuser" class="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' );?>" class="button" onclick="return validation();" /></td></tr>
    
     <input  name="userId" type="hidden" value="<?php echo $dt_user->id; ?>" />
     <input  name="task" type="hidden" value="confirmchanges" />
     <input  name="type" type="hidden" value="" />
     <input  name="option" type="hidden" value="com_dtregister" />
     <input  name="Itemid" type="hidden" value="<?php echo $Itemid?>" />
     </form>
    </table>
   <?php
   if(${$field_used._s_country}){
   ?>
    <script type="text/javascript">
	  //<![CDATA[
	   DTjQuery.noConflict();
DTjQuery(function(){
  DTjQuery('.upload').live('click',function(){
	   
	   DTjQuery(this.form).attr('target','fileupload');
	   prevtask = DTjQuery(this.form.task).val();
	   prevtype = DTjQuery(this.form.type).val();
	   var filesizes = DTjQuery(this).attr('filesize');
	   var filetype = DTjQuery(this).attr('filetype');
	   var name = DTjQuery(this).attr('filename');
	  
	   DTjQuery(this.form.type).val(name+'|'+filesizes+'|'+filetype);
	   
	   DTjQuery(this.form.task).val('fileupload');
	   DTjQuery(this.form.option).val('com_dtregister');
	   DTjQuery(this.form.option).val('com_dtregister');
	   
	   DTjQuery(this.form).submit();
	   
	   DTjQuery(this.form.task).val(prevtask);
	   DTjQuery(this.form.type).val(prevtype);
	   DTjQuery(this.form).attr('target','');
	   return false;
	});
})
    if(typeof(document.frmcart.country) != 'undefined')
	document.frmcart.country.value = "<?php echo $dt_user->userCountry?>";
	//]]>
  </script>
  <?php
  }
  ?>
    <?php
   
}

function listmembers($option){
   
   global $Itemid , $mainframe ;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $user	 =& JFactory::getUser();
   if ($user->get('id') == 0) {
	  $url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);
	  return;
   }
   $id=JRequest::getVar( 'id' );
   $dt_user =  new DT_User($id);
   if(!isset($_SESSION['billinginfo']['register']['members']) || count($_SESSION['billinginfo']['register']['members']) < 1 ){
     $members = $dt_user->get_members();
	 $_SESSION['billinginfo']['register']['members'] = $members;
	 
	 $members = $_SESSION['billinginfo']['register']['members'] ;
	 
   }else{
     $members = $_SESSION['billinginfo']['register']['members'] ;
   }
   
    $html = "" ;
   foreach($members as $key => $member){
     if(isset($member->remove) && $member->remove == 1){
	   continue ;
	 }
	  $edit = JHtml::link("index.php?option=com_dtregister&task=editmember&key=".$key."&Itemid=".$Itemid,'<img border="0"  src="'.JURI::root(true).'/images/M_images/edit.png" alt="'.JText::_( 'DT_EDIT').'" />');
	  $link = '<img border="0"  src="'.JURI::root(true).'/components/com_dtregister/assets/images/publish_x.png" alt="'.JText::_( 'DT_CANCEL').'" />'; 
      $html .= '<tr>
	             <td>'.$edit.'</td>
	             <td>'.$member->firstname.'</td><td>'.$member->lastname.'</td>
				 <td>'.$member->email.'</td>';
				 if($m_s_phone){
				    $html .= '<td>'.$member->phone.'</td>';
				 }
				 if($m_s_city){
				    $html .='<td>'.$member->city.'</td>' ;
				 }
        $html .='<td><a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=removemember&id='.$key,$xhtml_url ).'" >'.$link.'</a></td>
	          </tr>';
   }
   
   $evt =  new Event($dt_user->eventId);
   ?>
   
<div class="componentheading"><?php echo JText::_( 'DT_EDIT_RECORD' );?>: <?php echo $evt->summary; ?></div>
   <table>
     <tr>
       <td colspan="5">
          
          <a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=dtregedit&id='.$id,$xhtml_url ); ?>"><?php echo JText::_( 'DT_EDIT_BILLINGINFO') ?></a>
          
          &nbsp;|&nbsp;<a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=addmember&id='.$id,$xhtml_url ) ; ?>"><?php echo JText::_( 'DT_ADDMEMBER') ?></a>
       </td>
     </tr> 
     <tr>
     <th>&nbsp;
      
     </th>
     <th><?php echo JText::_( 'DT_FIRSTNAME') ?></th><th><?php echo JText::_( 'DT_LASTNAME') ?></th><th><?php echo JText::_( 'DT_EMAIL') ?></th>
     
     <?php if($m_s_phone){ ?>
     <th><?php echo JText::_( 'DT_PHONE') ?></th>
     <?php } ?>
     <?php if($m_s_city){ ?>
     <th><?php echo JText::_( 'DT_CITY') ?></th>
     <?php } ?>
     <th><?php echo JText::_( 'DT_REMOVE') ?></th>
     </tr>
     <?php echo $html;?>  
   </table>
   
   <?php
   
}

function saveuser($option,$verified=0){
   ob_start();
   global $Itemid , $mainframe ,$now;
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User(null,$dt_user->eventId);
   if(isset($_SESSION['register']['cancel_paying_amount'])){
      savecancel($dt_user->payment_type,1);
     
   }
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   
   //$dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
  // $dt_user = new DT_User($user->userId);
  
   //$dt_user->due_payment += $_SESSION['billinginfo']['register']['feechanges'];
   $old_fee =  $dt_user->get_amount();
   $dt_user->save( $dt_user );
    
   // save field verified and payment dues .
   
   $amount = $_SESSION['billinginfo']['register']['feechanges'];
   $new_fee = $amount ;
   $dt_user->set_amount($amount);
   $dt_user->save_field('paid_amount',($dt_user->paid_amount + $_SESSION['billinginfo']['register']['pay_amount']));
    
   if($dt_user->userType=='G' || count($_SESSION['billinginfo']['register']['members']) > 0){
      $members = $_SESSION['billinginfo']['register']['members'];
	  
	  foreach($members as $key => $member){
          
		  $memobj = new Member($member->groupMemberId);
		
		  if(isset($member->remove) && $member->remove == 1 && $memobj->id != ""){
			 $memobj->delete() ;
			 continue ;
		  }
		  if($member->groupMemberId==""){
		     unset($member->id);
		     $data = (array)$member;
			  $data['groupUserId'] = $dt_user->getGroup() ;
         $memobj->set($data);
		     $memobj->add($memobj);
			   continue ;  
		  }
		  if($member->groupMemberId != ""){
		     $data = (array)$member ;
			   $data['groupUserId'] = $dt_user->getGroup() ; 
		     $memobj->set($data);
         $memobj->save($memobj);
		  }
		  
	  }
   }
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   
	$history = array(
	         'user_id'=>$dt_user->id,
					 'type'=>$_SESSION['register']['payment_type'],
					 'amount'=>$_SESSION['billinginfo']['register']['pay_amount'],
					 'payment_date'=>$now->toFormat("%Y-%m-%d"),
		             'reason'=>'changes',
					 'transaction_id'=>(isset($_SESSION['register']['transaction_id']))?$_SESSION['register']['transaction_id']:''
	          );
   
	$database = &JFactory::getDBO();


    $row = new DThistory( $database );
	
	$row->bind( $history);
	
	$row->store( $history);
	
	unset($_SESSION['billinginfo']);
	unset($_SESSION['register']);
	
	change_email($dt_user,$history,$old_fee );
	$mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,JText::_( 'DT_RECORD_CHANGE_SUCCESSFUL') ); 
   
   
}

function confirmpay($option){
  
  global $Itemid , $mainframe;
  
  if($_POST['amount_paying']){
        $id = JRequest::getVar('id') ;
        $dt_user_old =  new DT_User(JRequest::getVar('id'));
		if(isset($_POST['partial']) && $_POST['partial']==1){
		   $amount = amount_filter($_POST['amount_paying']) ;
		}else{
		   $amount = $_POST['due_amount'];
		}
        $_SESSION['register']['due_paying_amount'] = $_POST['amount_paying'] ; 
		$_SESSION['billinginfo']['register']['user'] = serialize($dt_user_old);
		
        $mainframe->redirect("index.php?option=com_dtregister&task=due_payment&id=".$id."&Itemid=".$Itemid) ;
  }
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
  $dt_user_old =  new DT_User(JRequest::getVar('id'));
  $dt_user_old->event->over_ride_global();
        
		$currency_symbol = currency_symbol($currency_code);
	    if($currency_symbol!=""){
		   $currency_code = "";
		}
	
    $amount = $dt_user_old->get_amount();
	
	$due = $amount - $dt_user_old->paid_amount ;
	
	 ?>
      <div class="componentheading"> <?php echo JText::_( 'DT_MAKE_PAYMENT'); ?>: <?php echo $dt_user_old->event->summary; ?> (<?php echo get_date($dt_user_old->event->dtstart,$dt_user_old->event->dtend); ?>)</div>
      <table>
       <tr>
         <td> 
         <?php echo JText::_( 'DT_PANEL_PAYMENT_MSG'); ?>
         </td>
       </tr>
      </table>
      <form name="frmcart" method="post" action="index.php">
     <table>
     <tr><td><?php echo JText::_( 'DT_AMOUNT_DUE' ); ?>:</td><td><input type="radio" name="partial" value="0" /><?php echo $currency_symbol. numberFormat($due,2)." ".$currency_code;;?></td></tr>
     <tr><td>
	 
     <input type="hidden" name="due_amount" value="<?php echo $due; ?>" />
	 <?php echo JText::_( 'DT_AMOUNT_OTHER' ); ?>:</td><td><input type="radio" name="partial" checked="checked" value="1" /><input type="text" name="amount_paying" value="<?php echo numberFormat($due,2) ?>" /></td></tr>
     <tr><td><?php echo JText::_( 'DT_FIRSTNAME' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userFirstName);?></td></tr>

<tr><td><?php echo JText::_( 'DT_LASTNAME' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userLastName);?></td></tr>

<tr><td><?php echo JText::_( 'DT_ORGANIZATION' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userOrganization);?></td></tr>

<tr><td><?php echo JText::_( 'DT_ADDRESS' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userAddress);?></td></tr>

<tr><td><?php echo JText::_( 'DT_CITY' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userCity);?></td></tr>

<tr><td><?php echo JText::_( 'DT_STATE' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userState);?></td></tr>
<tr><td><?php echo JText::_( 'DT_COUNTRY' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userCountry);?></td></tr>

<tr><td><?php echo JText::_( 'DT_ZIPCODE' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userZip);?></td></tr>

<tr><td><?php echo JText::_( 'DT_PHONE' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userPhone);?></td></tr>

<tr><td><?php echo JText::_( 'DT_EMAIL' ); ?>:</td><td><?php echo stripslashes($dt_user_old->userEmail);?></td></tr>
<?php
if($dt_user_old->userType=='G'){
 $field_type = "B";
}else{
  $field_type = "I";
}
echo $dt_user_old->event->field_view($field_type,$dt_user_new);
?>

     <input  name="id" type="hidden" value="<?php echo $dt_user_old->id; ?>" />
     <input  name="task" type="hidden" value="confirmpay" />
     <input  name="type" type="hidden" value="paymentoptions" />
     <input  name="option" type="hidden" value="com_dtregister" />
     <input  name="Itemid" type="hidden" value="<?php echo $Itemid?>" />
     
   </table>
  
   <table>
<?php

$arrFields = array (
            
			'title' 	=> array('title', JText::_( 'DT_TITLE' ), 'm_s_title', 'm_r_title',JText::_( 'DT_ENTER_TITLE' )),
			
			'firstname' 	=> array('firstname', JText::_( 'DT_FIRSTNAME' ), 'm_s_firstname', 'm_r_firstname',JText::_( 'DT_ENTER_FNAME' )),

			'lastname' 	=> array('lastname', JText::_( 'DT_LASTNAME' ), 'm_s_lastname', 'm_r_lastname',JText::_( 'DT_ENTER_LNAME' )),

			'organization' 	=> array('organization', JText::_( 'DT_ORGANIZATION' ), 'm_s_organization', 'm_r_organization',JText::_( 'DT_ENTER_ORGANIZATION' )),

			'address' 	=> array('address', JText::_( 'DT_ADDRESS' ), 'm_s_address', 'm_r_address',JText::_( 'DT_ENTER_ADDRESS' )),
			
			'address2' 	=> array('address2', JText::_( 'DT_ADDRESS2' ), 'm_s_address2', 'm_r_address2',JText::_( 'DT_ENTER_ADDRESS2' )),

			'city' 	=> array('city', JText::_( 'DT_CITY' ), 'm_s_city', 'm_r_city',JText::_( 'DT_ENTER_CITY' )),

			'state' 	=> array('state', JText::_( 'DT_STATE' ), 'm_s_state', 'm_r_state',JText::_( 'DT_ENTER_STATE' )),

			'zip' 	=> array('zip', JText::_( 'DT_ZIPCODE' ), 'm_s_zip', 'm_r_zip',JText::_( 'DT_ENTER_ZIP' )),

			 'country' 	=> array('country', JText::_( 'DT_COUNTRY' ), 'm_s_country', 'm_r_country',JText::_( 'DT_ENTER_COUNTRY' )),

			'email' 	=> array('email', JText::_( 'DT_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			'cemail' 	=> array('cemail', JText::_( 'DT_CONFIRM_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			'phone'	=> array('phone', JText::_( 'DT_PHONE' ), 'm_s_phone', 'm_r_phone',JText::_( 'DT_ENTER_PHONE' ))

		);

//print_R($dt_user_new);
//print_R($_SESSION['billinginfo']['register']['members']);
   if($dt_user_new->userType=='G'){
   $fields = $dt_user_old->event->get_group_custom_field();
   foreach((array)$fields as $key => $value){
      $temp[$value->name] = $value;
   }
   
   $i  = 1;
   $id_fields = array('groupMemberId','groupUserId','groupId','useid');
    $members = $dt_user_old->get_members();
    foreach((array)$members as $key => $value){
	   
	   echo "<tr><td colspan=2><br /><u>".JText::_( 'DT_MEMBER' )." {$i}</u></td></tr>";
	   if(!isset($value->remove) && $value->remove !=1){
	         
	       foreach ((array)$value as $key2 => $value2){
	     
		  if($value2!="" && !in_array($key2,$id_fields)){
		     if(isset($temp[$key2])){
			   echo "<tr><td>" . stripslashes($temp[$key2]->label) . ": </td><td>". stripslashes($value2) ."</td></tr>";
			 }else{
		       echo "<tr><td>" . $arrFields[stripslashes($key2)][1]  . ": </td><td>". stripslashes($value2) ."</td></tr>";
			 }
		  }
		   
	   }
	       $i++ ;
	   } 
	}
	
 ?>
 <?php
   }
   ?>
   </table>
   <table>
   
   <tr><td colspan="2" align="center"><input type="button" class="button" name="back" onclick="window.location='<?php  echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=history&back=1',$xhtml_url ) ; ?>'" value="<?php echo JText::_( 'DT_BACK' );?>" />&nbsp;&nbsp;<input type="submit"  name="saveuser" class="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' );?>" /></td></tr>
  </table>
  </form>
  <?php

}

function confirmchanges($option){

   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
  global $Itemid;
    global $currency_code ;
	
	$dt_user_old =  new DT_User(JRequest::getVar('userId'));
	
	$dt_user_new =  unserialize($_SESSION['billinginfo']['register']['user']);
	$dt_user_new->DT_User(null,$dt_user_new->eventId);
	$dt_user_new->event->over_ride_global();
	$currency_symbol = currency_symbol($currency_code);
	 if($currency_symbol!=""){
	   $currency_code = "";
	}else{
	  $currency_code = " ".$currency_code;
	}
	$backlink = "window.location='".JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=dtregedit&back=1&id='.$dt_user_new->id,$xhtml_url )."'";
	if(JRequest::getVar('cancel')==1){
	   
	   $panel_msg = JText::_( 'DT_PANEL_CANCEL_MSG') ;
	   $new_amount = $_SESSION['register']['set_fee'] ; 
	  $backlink = "window.location='". JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=history&back=1',$xhtml_url )."'";
	  $toplabel = JText::_( 'DT_CANCELLATION' ) ;
	  $feelabel = JText::_( 'DT_CANCEL_FEE' );
	  $totamount = $dt_user_old->get_amount();
      $fee = cancel_fee($totamount);
	  $fee += $dt_user_new->event->getTaxAmount($fee);
	  $paying = $_SESSION['billinginfo']['register']['pay_amount'] ;
	  
	}else{
	
		//$dt_code =  new DiscountCode($dt_user_old->discount_code_id);
		$panel_msg = JText::_( 'DT_PANEL_CONFIRMATION_MSG') ;
		$toplabel = JText::_( 'DT_EDIT_RECORD' ) ;
		$data=Jrequest::get('post');
		$feelabel = JText::_( 'DT_CHANGE_FEE' );
		$dt_user_new->set($data);
		$old_mem_cnt = count($dt_user_new->get_members());
		
		$new_mem_cnt = count_members();
		
		if($old_mem_cnt > 0 && $new_mem_cnt > 0){
		  
			if($old_mem_cnt != $new_mem_cnt){
			   
			   $tot_mem_cnt = $new_mem_cnt - $old_mem_cnt ;
			  
			   if($tot_mem_cnt > 0 ){
				   $fee  = $dt_user_new->event->get_total_fee($new_mem_cnt,$dt_user_new->user_id,$dt_user_new->register_date);
			
				   $custom_fee = $dt_user_new->get_custom_fee($dt_user_new,$_SESSION['billinginfo']['register']['members']);
				   
				   $new_amount =  $fee + $custom_fee;
				   
			   }else{
				  
					$fee  = $dt_user_new->event->get_total_fee(abs($tot_mem_cnt),$dt_user_new->user_id,$dt_user_new->register_date);
				
					
					$custom_fee = $dt_user_new->get_custom_fee($dt_user_new,$_SESSION['billinginfo']['register']['members']);
					
					$new_amount =  $fee + $custom_fee;
					
				  
			   }
			  
			}else{
			   $custom_fee = $dt_user_new->get_custom_fee($dt_user_new,$_SESSION['billinginfo']['register']['members']);
			   $old_custom_fee = $dt_user_old->get_custom_fee($dt_user_old,$dt_user_old->get_members());
			   $new_amount = $dt_user_new->get_amount() + $custom_fee - $old_custom_fee;
			   
			}
		
		}else{
		       $custom_fee = $dt_user_new->get_custom_fee($dt_user_new,$_SESSION['billinginfo']['register']['members']);
			   $old_custom_fee = $dt_user_old->get_custom_fee($dt_user_old,$dt_user_old->get_members());
			   $new_amount = $dt_user_new->get_amount() + $custom_fee - $old_custom_fee;
		}
		
		if(1){
		   $old_fee = $dt_user_old->get_amount() ;
		   $new_amount += $dt_user_old->event->getTaxAmount(($new_amount - $old_fee));
		  $paying = change_fee($new_amount) ;
		  $chg_fee = $paying += $dt_user_old->event->getTaxAmount($paying);
		  $new_amount.' '.$dt_user_old->paid_amount ;
		    $fee =  $paying ;
		  $paying +=  $new_amount  - $dt_user_old->paid_amount ;
		  
		  // echo "<br />paying ". $paying +=  $new_amount - $old_fee - $dt_user_old->paid_amount ;
		   $new_fee = $new_amount;
		  //$new_amount += change_fee($new_amount);
		}else{
		   $fee = 0 ;
		}
		
		$not_paying_methods =  array('At_door','Mail','Phone','Pay Later');
		
		if(in_array($dt_user_old->payment_type,$not_paying_methods)){
		   $paying = 0 ;
		}
		
	}
 
	//echo "<pre>";
	//print_R($dt_user_new);
	//echo "</pre>";
	
	$_SESSION['billinginfo']['register']['user'] = serialize($dt_user_new) ; 
	$_SESSION['billinginfo']['register']['feechanges'] = $new_amount + $chg_fee;
	$_SESSION['billinginfo']['register']['pay_amount'] = $paying;
	if(($new_amount - $dt_user_old->paid_amount) > 0){
	   $feepaylabel = JText::_( 'DT_ADDED_FEE' );
	}elseif(($new_amount - $dt_user_old->paid_amount) < 0 ){
	   $feepaylabel = JText::_( 'DT_REFUND_DUE' );
	}else{
	
	}
	
	 ?>
     
       <div class="componentheading"><?php echo $toplabel;?>: <?php echo $dt_user_new->event->summary; ?></div>
      
      <table>
        <tr>
         <td>
           <?php echo $panel_msg; ?>
         </td>
        </tr>
      </table>
      <form name="frmcart" method="post" action="index.php">
     <table>
     <tr>
       <td class="fieldlabel"> <?php echo JText::_( 'DT_ORIGINAL_FEE' ) ?>:</td><td> <?php echo  $currency_symbol. numberFormat($previous_amount = $dt_user_old->get_amount()).$currency_code; ?>
       </td>
     </tr>
     <?php
     if(JRequest::getVar('cancel',0)!=1){
	  ?>
      <tr>
       <td class="fieldlabel"> <?php echo JText::_( 'DT_NEW_FEE' ) ?>:</td><td> <?php echo  $currency_symbol. numberFormat($new_amount).$currency_code; ?>
       </td>
     </tr>
      <?php
	 }
	 ?>
     <tr>
       <td class="fieldlabel"> <?php echo JText::_( 'DT_AMOUNT_PAID' ) ?>:</td><td> <?php echo  $currency_symbol. numberFormat($dt_user_old->paid_amount).$currency_code; ?>
       </td>
     </tr>
      <tr>
       <td class="fieldlabel"> <?php echo $feelabel; ?>:</td><td> <?php echo  $currency_symbol. numberFormat($fee).$currency_code; ?>
       </td>
     </tr>
     
     <?php
     
	 if(0){
	  
	 ?>
	  <tr><td><?php echo $feepaylabel; ?>:</td><td><?php echo $currency_symbol.numberFormat(abs($_SESSION['billinginfo']['register']['pay_amount']),2).$currency_code;?></td></tr>
     <?php
	 }
	 ?>
     <tr><td class="fieldlabel" ><?php echo JText::_( 'DT_TITLE' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userTitle);?></td></tr> 
     <tr><td class="fieldlabel" ><?php echo JText::_( 'DT_FIRSTNAME' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userFirstName);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_LASTNAME' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userLastName);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ORGANIZATION' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userOrganization);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userAddress);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ADDRESS2' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userAddress2);?></td></tr> 

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_CITY' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userCity);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_STATE' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userState);?></td></tr>
<tr><td><?php echo JText::_( 'DT_COUNTRY' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userCountry);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_ZIPCODE' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userZip);?></td></tr>
 
<tr><td class="fieldlabel"><?php echo JText::_( 'DT_PHONE' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userPhone);?></td></tr>

<tr><td class="fieldlabel"><?php echo JText::_( 'DT_EMAIL' ); ?>:</td><td><?php echo stripslashes($dt_user_new->userEmail);?></td></tr>
<?php
if($dt_user_new->userType=='G'){
 $field_type = "B";
}else{
  $field_type = "I";
}
echo $dt_user_new->event->field_view($field_type,$dt_user_new);
?>

     <input  name="userId" type="hidden" value="<?php echo $dt_user_new->id; ?>" />
     <input  name="task" type="hidden" value="paymentchanges" />
     <input  name="type" type="hidden" value="paymentoptions" />
     <input  name="option" type="hidden" value="com_dtregister" />
     <input  name="Itemid" type="hidden" value="<?php echo $Itemid?>" />
     
   </table>
  
   <table>
<?php
$arrFields = array (
            
			'title' 	=> array('title', JText::_( 'DT_TITLE' ), 'm_s_title', 'm_r_title',JText::_( 'DT_ENTER_TITLE' )),
			
			'firstname' 	=> array('firstname', JText::_( 'DT_FIRSTNAME' ), 'm_s_firstname', 'm_r_firstname',JText::_( 'DT_ENTER_FNAME' )),

			'lastname' 	=> array('lastname', JText::_( 'DT_LASTNAME' ), 'm_s_lastname', 'm_r_lastname',JText::_( 'DT_ENTER_LNAME' )),

			'organization' 	=> array('organization', JText::_( 'DT_ORGANIZATION' ), 'm_s_organization', 'm_r_organization',JText::_( 'DT_ENTER_ORGANIZATION' )),

			'address' 	=> array('address', JText::_( 'DT_ADDRESS' ), 'm_s_address', 'm_r_address',JText::_( 'DT_ENTER_ADDRESS' )),
			
			'address2' 	=> array('address2', JText::_( 'DT_ADDRESS2' ), 'm_s_address2', 'm_r_address2',JText::_( 'DT_ENTER_ADDRESS2' )),

			'city' 	=> array('city', JText::_( 'DT_CITY' ), 'm_s_city', 'm_r_city',JText::_( 'DT_ENTER_CITY' )),

			'state' 	=> array('state', JText::_( 'DT_STATE' ), 'm_s_state', 'm_r_state',JText::_( 'DT_ENTER_STATE' )),

			'zip' 	=> array('zip', JText::_( 'DT_ZIPCODE' ), 'm_s_zip', 'm_r_zip',JText::_( 'DT_ENTER_ZIP' )),

			 'country' 	=> array('country', JText::_( 'DT_COUNTRY' ), 'm_s_country', 'm_r_country',JText::_( 'DT_ENTER_COUNTRY' )),

			'email' 	=> array('email', JText::_( 'DT_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			'cemail' 	=> array('cemail', JText::_( 'DT_CONFIRM_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			'phone'	=> array('phone', JText::_( 'DT_PHONE' ), 'm_s_phone', 'm_r_phone',JText::_( 'DT_ENTER_PHONE' ))

		);
//print_R($dt_user_new);

   if($dt_user_new->userType=='G'){
   $fields = $dt_user_new->event->get_group_custom_field();
   foreach((array)$fields as $key => $value){
      $temp[$value->name] = $value;
   }
   
   $i  = 1;
   
   $id_fields = array('groupMemberId','groupUserId','groupId','useid');
    foreach((array)$_SESSION['billinginfo']['register']['members'] as $key => $value){
	   
	   if(!isset($value->remove) && $value->remove !=1){
	         echo "<tr><td colspan=2><br /><u>".JText::_( 'DT_MEMBER' )." {$i}</u></td></tr>";
	       foreach ((array)$value as $key2 => $value2){
	    //  echo "<tr><td colspan=2><br /><u>".JText::_( 'DT_MEMBER' )." {$key2}</u></td></tr>";
		  if($value2!="" && !in_array($key2,$id_fields)){
		     if(isset($temp[$key2])){
			   echo "<tr><td>" . stripslashes($temp[$key2]->label) . ": </td><td>". stripslashes($value2) ."</td></tr>";
			 }else{
		       if(isset($arrFields[stripslashes($key2)]))
			   echo "<tr><td>" . $arrFields[stripslashes($key2)][1] . ": </td><td>". stripslashes($value2) ."</td></tr>";
			 }
		  }
		   
	   }
	       $i++ ;
	   } 
	}
	
 ?>
 <?php
   }
   ?>
   </table>
   <table>
   <tr><td colspan="2" align="center"><input type="button" class="button" onclick="<?php echo $backlink; ?>" name="back" value="<?php echo JText::_( 'DT_BACK' );?>" />&nbsp;&nbsp;<input type="submit" name="saveuser" class="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' );?>" /></td></tr>
  </table>
  </form>
  <?php
}

function editmember($option){
   
   global $Itemid , $mainframe;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $id = JRequest::getVar( 'key' );
   
   $member = $_SESSION['billinginfo']['register']['members'][$id];
   
   ?>
   <link rel="stylesheet" href="<?php echo JURI::root(true) ?>/media/system/css/calendar-jos.css" type="text/css"  title="green"  media="all" />
<script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/mootools.js"></script>
  <script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/calendar.js"></script>

  <script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/calendar-setup.js"></script>

  <script type="text/javascript">
       //<![CDATA[
		//window.addEvent('domready', function(){ var JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false}); });

Calendar._DN = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");Calendar._SDN = new Array ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"); Calendar._FD = 0;	Calendar._MN = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");	Calendar._SMN = new Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");Calendar._TT = {};Calendar._TT["INFO"] = "About the Calendar";

 		Calendar._TT["ABOUT"] =

 "DHTML Date/Time Selector\n" +

 "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +

"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +

"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +

"\n\n" +

"Date selection:\n" +

"- Use the \xab, \xbb buttons to select year\n" +

"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +

"- Hold mouse button on any of the above buttons for faster selection.";

Calendar._TT["ABOUT_TIME"] = "\n\n" +

"Time selection:\n" +

"- Click on any of the time parts to increase it\n" +

"- or Shift-click to decrease it\n" +

"- or click and drag for faster selection.";

		Calendar._TT["PREV_YEAR"] = "Click to move to the previous year. Click and hold for a list of years.";Calendar._TT["PREV_MONTH"] = "Click to move to the previous month. Click and hold for a list of the months.";	Calendar._TT["GO_TODAY"] = "Go to today";Calendar._TT["NEXT_MONTH"] = "Click to move to the next month. Click and hold for a list of the months.";Calendar._TT["NEXT_YEAR"] = "Click to move to the next year. Click and hold for a list of years.";Calendar._TT["SEL_DATE"] = "Select a date";Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";Calendar._TT["PART_TODAY"] = " (Today)";Calendar._TT["DAY_FIRST"] = "Display %s first";Calendar._TT["WEEKEND"] = "0,6";Calendar._TT["CLOSE"] = "Close";Calendar._TT["TODAY"] = "Today";Calendar._TT["TIME_PART"] = "(Shift-)Click or Drag to change the value.";Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%M-%D"; Calendar._TT["TT_DATE_FORMAT"] = "%A, %B %e";Calendar._TT["WK"] = "wk";Calendar._TT["TIME"] = "Time:";
//]]>
  </script>
  <?php
  $arrFields = array (
            
			1 	=> array('title', JText::_( 'DT_TITLE' ), 'm_s_title', 'm_r_title',JText::_( 'DT_ENTER_TITLE' )),
			
			2 	=> array('firstname', JText::_( 'DT_FIRSTNAME' ), 'm_s_firstname', 'm_r_firstname',JText::_( 'DT_ENTER_FNAME' )),

			3 	=> array('lastname', JText::_( 'DT_LASTNAME' ), 'm_s_lastname', 'm_r_lastname',JText::_( 'DT_ENTER_LNAME' )),

			4 	=> array('organization', JText::_( 'DT_ORGANIZATION' ), 'm_s_organization', 'm_r_organization',JText::_( 'DT_ENTER_ORGANIZATION' )),

			5 	=> array('address', JText::_( 'DT_ADDRESS' ), 'm_s_address', 'm_r_address',JText::_( 'DT_ENTER_ADDRESS' )),
			
			6 	=> array('address2', JText::_( 'DT_ADDRESS2' ), 'm_s_address2', 'm_r_address2',JText::_( 'DT_ENTER_ADDRESS2' )),

			7 	=> array('city', JText::_( 'DT_CITY' ), 'm_s_city', 'm_r_city',JText::_( 'DT_ENTER_CITY' )),

			8 	=> array('state', JText::_( 'DT_STATE' ), 'm_s_state', 'm_r_state',JText::_( 'DT_ENTER_STATE' )),

			9 	=> array('zip', JText::_( 'DT_ZIPCODE' ), 'm_s_zip', 'm_r_zip',JText::_( 'DT_ENTER_ZIP' )),

			10 	=> array('country', JText::_( 'DT_COUNTRY' ), 'm_s_country', 'm_r_country',JText::_( 'DT_ENTER_COUNTRY' )),

			11 	=> array('email', JText::_( 'DT_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			12 	=> array('cemail', JText::_( 'DT_CONFIRM_EMAIL' ), 'm_s_email', 'm_r_email',JText::_( 'DT_ENTER_EMAIL' )),

			13	=> array('phone', JText::_( 'DT_PHONE' ), 'm_s_phone', 'm_r_phone',JText::_( 'DT_ENTER_PHONE' ))

		);
	 $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $evt = new Event($dt_user->eventId);  
  ?>
    <script src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>
    <script src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/js/textareaCounter.js" type="text/javascript"></script>
<div class="componentheading"><?php echo JText::_( 'DT_EDIT_RECORD' );?>: <?php echo $evt->summary; ?></div>
  <form name="frmcart" method="post" action="index.php" enctype="multipart/form-data">
   <table width="100%" cellpadding="2" cellspacing="2">
   <?php
     
	   $titles = explode("|",$titleoptions);
			    $temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

			  foreach($titles as $title){
	
				$temp[] = JHTML::_('select.option', $title, $title);
	
			  }
	        
			  $titles = $temp;
   
      foreach ($arrFields as $key=>$value){
            
			if ($$value[2]){
                  
				if($value[0]=='country'){

					require(JPATH_SITE.'/components/com_dtregister/country.htm');

				}else{

				?><tr><td width="30%" class="fieldlabel"><?php echo $value[1] . ' :';

					if ($$value[3]==1){

					?><span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span><?php

				}

					if('cemail'==$value[0]){

						$memberdata['cemail'] = $memberdata['email'];

					}

				?></td><td width="68%" align="left" >
                 <?php 
				  
				  if($value[0]=='title'){
				     echo JHTML::_('select.genericlist',$temp,'title', 'class="inputbox" size="1"', 'value', 'text',$member->{$value[0]}); 
				}else {
				 
				 ?> 
                  
                <input type="text" name="<?php echo $value[0]; ?>" value="<?php echo stripslashes($member->{$value[0]});?>" class="inputbox" />

                <?php } }?>

                </td><td width="2%" >&nbsp;</td></tr><?php

			}

		}	  
  ?>
   
    <?php
	
   $evt->read();
   echo $evt->field_html('M',$member);
	?>
    <tr><td colspan="3" align="center"><input onclick='window.location="<?php echo JRoute::_("index.php?option=com_dtregister&task=listmembers&id=".$dt_user->id); ?>"' name="" type="button" class="button" value="<?php echo JText::_( 'DT_BACK' ); ?>" />&nbsp;&nbsp;<input type="submit" class="button" onclick="return validateform()" name="savemember" value="<?php echo JText::_( 'DT_SAVE' );?>" /></td></tr>
    
     <input  name="key" type="hidden" value="<?php echo $id; ?>" />
     <input  name="task" type="hidden" value="savemember" />
     <input  name="type" type="hidden" value="" />
     <input  name="option" type="hidden" value="com_dtregister" />
     <input  name="Itemid" type="hidden" value="<?php echo $Itemid?>" />
     </form>
   </table>
  
   <script type="text/javascript">
      //<![CDATA[
     //jQuery.noConflict();
DTjQuery(function(){
  DTjQuery('.upload').live('click',function(){
	   
	   DTjQuery(this.form).attr('target','fileupload');
	   prevtask = DTjQuery(this.form.task).val();
	   prevtype = DTjQuery(this.form.type).val();
	   var filesizes = DTjQuery(this).attr('filesize');
	   var filetype = DTjQuery(this).attr('filetype');
	   var name = DTjQuery(this).attr('filename');
	  
	   DTjQuery(this.form.type).val(name+'|'+filesizes+'|'+filetype);
	   
	   DTjQuery(this.form.task).val('fileupload');
	   DTjQuery(this.form.option).val('com_dtregister');
	   DTjQuery(this.form.option).val('com_dtregister');
	   
	   DTjQuery(this.form).submit();
	   
	   DTjQuery(this.form.task).val(prevtask);
	   DTjQuery(this.form.type).val(prevtype);
	   DTjQuery(this.form).attr('target','');
	   return false;
	});
})
    if(typeof(document.frmcart.country) != 'undefined')
	document.frmcart.country.value = "<?php echo $member->country?>";
	//]]>
  </script>

  <script language="JavaScript" type="text/javascript">
   //<![CDATA[
var memberTotal=<?php echo count_members() ;?>;

function validateform()

{

	var currentMember=document.frmcart.current_member.value;
    
	<?php

		if($m_s_title && $m_r_title){	?>

			if(document.frmcart.title.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_TITLE' ); ?>");

			document.frmcart.title.focus();

			return;

			}

	<?php } ?>
	
	<?php if($m_s_firstname && $m_r_firstname){ ?>

			if(document.frmcart.firstname.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_FNAME' ); ?>");

				document.frmcart.firstname.focus();

				return ;

			}

	<?php }

		if($m_s_lastname && $m_r_lastname){	?>

			if(document.frmcart.lastname.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_LNAME' ); ?>");

				document.frmcart.lastname.focus();

				return;

			}

	<?php }

		if($m_s_organization && $m_r_organization){	?>

			if(document.frmcart.organization.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ORGANIZATION' ); ?>");

			document.frmcart.organization.focus();

			return;

			}

	<?php }

		if($m_s_address && $m_r_address){ ?>

			if(document.frmcart.address.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS' ); ?>");

				document.frmcart.address.focus();

				return;

			}

	<?php } ?>
   <?php

		if($m_s_address2 && $m_r_address2){	?>

			if(document.frmcart.address2.value==""){

			alert ("<?php echo JText::_( 'DT_ENTER_ADDRESS2' ); ?>");

			document.frmcart.adddress2.focus();

			return;

			}

	<?php } ?>
	
       <?php
		if($m_s_city && $m_r_city){ ?>

			if(document.frmcart.city.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_CITY' ); ?>");

		    	document.frmcart.city.focus();

				return;

			}

	<?php }

		if($m_s_state && $m_r_state)

		{

		?>

			if(document.frmcart.state.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_STATE' ); ?>");

				document.frmcart.state.focus();

				return;

			}

		<?php

		}

		if($m_s_zip && $m_r_zip)

		{

		?>

			if(document.frmcart.zip.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_ZIP' ); ?>")

				document.frmcart.zip.focus();

				return false;

			}

		<?php

		}

		if($m_s_email  && $m_r_email)

		{

		?>

			if(document.frmcart.email.value==""){

				alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

				document.frmcart.email.focus();

				return;

			}

			if(document.frmcart.cemail.value==""){

		    alert ("<?php echo JText::_( 'DT_ENTER_EMAIL' ); ?>");

		    document.frmcart.cemail.focus();

		    return;

			}

			if(document.frmcart.email.value!=document.frmcart.cemail.value){

			alert("<?php echo JText::_( 'DT_EMAIL_MATCH' ); ?>");

			document.frmcart.cemail.focus();

			return;

			}

			if(document.frmcart.email.value!=""){

			var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;

			var returnval=emailfilter.test(document.frmcart.email.value)

				if (returnval==false){

				alert("<?php echo JText::_( 'DT_INVALID_EMAIL' ); ?>");

				document.frmcart.email.select();

				document.frmcart.email.focus();

				return ;

				}

			}

		<?php

		}

		if($m_s_phone && $m_r_phone){ ?>

			if(document.frmcart.phone.value==""){

				alert("<?php echo JText::_( 'DT_ENTER_PHONE' ); ?>");

				document.frmcart.phone.focus();

				return;

			}

		<?php
         echo  $evt->javavalidation;
		
		}
        ?>
		document.frmcart.submit();

	}	// END Function validateform()
//]]>
</script>

<?php
}
function savemember($option){
    
	global $Itemid , $mainframe;
	$id = JRequest::getVar('key');
   	$member_old =  $_SESSION['billinginfo']['register']['members'][$id];
	$dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
	$dt_user->DT_User($dt_user->id,$dt_user->eventId);
    $evt = new Event($dt_user->eventId);
    $evt->read();
	$member_new =  new Member($member_old->groupMemberId);
	$member_new->read();
	
	$data=Jrequest::get('post');
	$data['groupUserId'] = $dt_user->getGroup() ; 
	$member_new->set($data);
	$fld = new Custom_field();
	 $fields=array() ;
			
     $fld->getAllFields($dt_user->eventId,'M',false,0,$fields) ;
			
	 $rowCustoms = $fields ;
	 
	 foreach($rowCustoms as $rowCustom){
	    
		$name=$rowCustom->name;
		$values=$rowCustom->values;
        $arrValues=explode("|",$values);
        $postedValue=JRequest::getVar($name,'','post');
        if(in_array($rowCustom->type,array(1,3,4))){
			   	
				if(!is_array($postedValue)){
				   	
					$postval = array($postedValue);
			    }else{
					$postval = $postedValue ;
				}
				if(!is_array($member_old->{$name})){
				    $member_old->{$name} = array($member_old->{$name});	
				}
            foreach($arrValues as $key=>$val){
				
				   if(in_array($val,$postval)){
					    if(!in_array($val ,$member_old->{$name})){
						  if(!isset($_SESSION['register']['option_used'][$rowCustom->id][$key])){
						
							   $_SESSION['register']['option_used'][$rowCustom->id][$key] = 1 ;
							 
						  }else{
							  
								$_SESSION['register']['option_used'][$rowCustom->id][$key]++ ;
						  }
						}
				   }else{
					   if(in_array($val ,$member_old->{$name})){
						    $_SESSION['register']['option_used'][$rowCustom->id][$key]-- ;  
					   }       
				   }
				  
				   	
				}

	      }
	 }
			
	$newfee = $evt->get_custom_fields_fee((array)$member_old,'M');
	$oldfee = $evt->get_custom_fields_fee((array)$member_new,'M');
	$_SESSION['billinginfo']['register']['members'][$id] = (object)(array)$member_new;
	//$member_new->save($member_new );
	$mainframe->redirect("index.php?option=com_dtregister&Itemid=".$Itemid."&id=".$dt_user->userId."&task=listmembers");
}

function savenewmember($option){ 
   global $Itemid , $mainframe;
   $dt_user =  unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $member =  new Member();
   $data=Jrequest::get('post');
   $data['groupUserId'] = $dt_user->getGroup() ; 
   $member->set($data);
   $cnt = count($_SESSION['billinginfo']['register']['members']);
   $_SESSION['billinginfo']['register']['members'][$cnt] = (object)(array)$member ;
     $fld = new Custom_field();
	 $fields=array() ;
			
     $fld->getAllFields($dt_user->eventId,'M',false,0,$fields) ;
			
	 $rowCustoms = $fields ;
	 
	 foreach($rowCustoms as $rowCustom){
	    
		$name=$rowCustom->name;
		$values=$rowCustom->values;
        $arrValues=explode("|",$values);
        $postedValue=JRequest::getVar($name,'','post');
        if(in_array($rowCustom->type,array(1,3,4))){
			   	
				if(!is_array($postedValue)){
				   	
					$postval = array($postedValue);
			    }else{
					$postval = $postedValue ;
				}
				
            foreach($arrValues as $key=>$val){
				
				   if(in_array($val,$postval)){
					    
						  if(!isset($_SESSION['register']['option_used'][$rowCustom->id][$key])){
						
							   $_SESSION['register']['option_used'][$rowCustom->id][$key] = 1 ;
							 
						  }else{
							  
								$_SESSION['register']['option_used'][$rowCustom->id][$key]++ ;
						  }
						
				   }
				  
				   	
				}

	      }
	 }
  // $member->add($member);
   //$memtot = count_members();
   /*$fee  = $dt_user->event->get_total_fee($memtot,$dt_user->user_id,$dt_user->register_date);
   $custom_fee = $dt_user->get_custom_fee();
   $dt_code =  new DiscountCode($dt_user->discount_code_id);
   $discount = $dt_code->get_discount_amount(($fee + $custom_fee));
   $amount = $fee + $custom_fee - $discount ;
   $dt_user->set_amount($amount);*/
   $mainframe->redirect("index.php?option=com_dtregister&Itemid=".$Itemid."&id=".$dt_user->userId."&task=listmembers");
   
}

function removemember($option){
   
   global $Itemid , $mainframe;
   $id = JRequest::getVar('id') ;
   $member  =  $_SESSION['billinginfo']['register']['members'][$id];
  // $member =  new Member($member->id);
   // $member->Member($member->id);
  
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $memtot  = count_members();
   if( $memtot <= 2){
      
	  $mainframe->redirect("index.php?option=com_dtregister&Itemid=".$Itemid."&id=".$dt_user->userId."&task=listmembers",JText::_( 'DT_MEMBER_REMOVE_ERROR' ));
   }
   
   $_SESSION['billinginfo']['register']['members'][$id]->remove = 1 ;
     $member = $_SESSION['billinginfo']['register']['members'][$id] ;
    $fld = new Custom_field();
	 $fields=array() ;
			
     $fld->getAllFields($dt_user->eventId,'M',false,0,$fields) ;
			
	 $rowCustoms = $fields ;
	 
	 foreach($rowCustoms as $rowCustom){
	    
		$name=$rowCustom->name;
		$values=$rowCustom->values;
        $arrValues=explode("|",$values);
        
        if(in_array($rowCustom->type,array(1,3,4))){
			   	
				
				if(!is_array($member->{$name})){
				    $member->{$name} = array($member->{$name});	
				}
            foreach($arrValues as $key=>$val){
				
				   
					   if(in_array($val ,$member->{$name})){
						    $_SESSION['register']['option_used'][$rowCustom->id][$key]-- ;  
					   }       
				  
				  
				   	
				}

	      }
	 }
   $mainframe->redirect("index.php?option=com_dtregister&Itemid=".$Itemid."&id=".$dt_user->userId."&task=listmembers");
   //$member->delete();
  // $dt_user = new DT_User($member->getUserId(),$dt_user->eventId);
   /*$memtot = count_members();
   $fee  = $dt_user->event->get_total_fee($memtot,$dt_user->user_id,$dt_user->register_date);
   $custom_fee = $dt_user->get_custom_fee();
   $dt_code =  new DiscountCode($dt_user->discount_code_id);
   $discount = $dt_code->get_discount_amount(($fee + $custom_fee));
   $amount = $fee + $custom_fee - $discount ;
   $dt_user->set_amount($amount);*/
    
}

function addmember($option){
  
  global $Itemid , $mainframe;
  include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $member =  new Member();
   //$member->read();
   //echo "<pre>";
    // print_r($member);
   //echo "</pre>"
   ?>
   <link rel="stylesheet" href="<?php echo JURI::root(true) ?>/media/system/css/calendar-jos.css" type="text/css"  title="green"  media="all" />
<script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/mootools.js"></script>
  <script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/calendar.js"></script>

  <script type="text/javascript" src="<?php echo JURI::root(true) ?>/media/system/js/calendar-setup.js"></script>

  <script type="text/javascript">
   //<![CDATA[
		//window.addEvent('domready', function(){ var JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false}); });

Calendar._DN = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");Calendar._SDN = new Array ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"); Calendar._FD = 0;	Calendar._MN = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");	Calendar._SMN = new Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");Calendar._TT = {};Calendar._TT["INFO"] = "About the Calendar";

 		Calendar._TT["ABOUT"] =

 "DHTML Date/Time Selector\n" +

 "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +

"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +

"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +

"\n\n" +

"Date selection:\n" +

"- Use the \xab, \xbb buttons to select year\n" +

"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +

"- Hold mouse button on any of the above buttons for faster selection.";

Calendar._TT["ABOUT_TIME"] = "\n\n" +

"Time selection:\n" +

"- Click on any of the time parts to increase it\n" +

"- or Shift-click to decrease it\n" +

"- or click and drag for faster selection.";

		Calendar._TT["PREV_YEAR"] = "Click to move to the previous year. Click and hold for a list of years.";Calendar._TT["PREV_MONTH"] = "Click to move to the previous month. Click and hold for a list of the months.";	Calendar._TT["GO_TODAY"] = "Go to today";Calendar._TT["NEXT_MONTH"] = "Click to move to the next month. Click and hold for a list of the months.";Calendar._TT["NEXT_YEAR"] = "Click to move to the next year. Click and hold for a list of years.";Calendar._TT["SEL_DATE"] = "Select a date";Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";Calendar._TT["PART_TODAY"] = " (Today)";Calendar._TT["DAY_FIRST"] = "Display %s first";Calendar._TT["WEEKEND"] = "0,6";Calendar._TT["CLOSE"] = "Close";Calendar._TT["TODAY"] = "Today";Calendar._TT["TIME_PART"] = "(Shift-)Click or Drag to change the value.";Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%M-%D"; Calendar._TT["TT_DATE_FORMAT"] = "%A, %B %e";Calendar._TT["WK"] = "wk";Calendar._TT["TIME"] = "Time:";
   
   //]]>
   </script>
  <?php
   $dt_user =unserialize($_SESSION['billinginfo']['register']['user']);
   $evt = new Event($dt_user->eventId);
  
  ?>
    
<div class="componentheading"><?php echo JText::_( 'DT_EDIT_RECORD' );?>: <?php echo $evt->summary; ?></div>
  <table>
    <tr>
     <td>
       <?php echo JText::_( 'DT_ADDMEMBER_DESC' ); ?>
     </td>
    </tr>
  </table>
  <form name="frmcart" method="post" action="index.php">
   <table>
   <?php if($m_s_firstname){?>
    <tr><td width="30%"><?php echo JText::_( 'DT_FIRSTNAME' ); ?>:</td><td width="69%"><input type="text" name="firstname" value="<?php echo stripslashes($member->firstname);?>" /></td><td width="2%" >&nbsp;</td></tr>
  <?php } ?>
  <?php if($m_s_lastname){?>
<tr><td width="30%"><?php echo JText::_( 'DT_LASTNAME' ); ?>:</td><td width="68%"><input type="text" name="lastname" value="<?php echo stripslashes($member->lastname);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_organization){?>
<tr><td width="30%"><?php echo JText::_( 'DT_ORGANIZATION' ); ?>:</td><td width="68%"><input type="text" name="organization" value="<?php echo stripslashes($member->organization);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_address){?>
<tr><td width="30%"><?php echo JText::_( 'DT_ADDRESS' ); ?>:</td><td width="68%"><input type="text" name="address" value="<?php echo stripslashes($member->address);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_city){?>
<tr><td width="30%"><?php echo JText::_( 'DT_CITY' ); ?>:</td><td width="68%"><input type="text" name="city" value="<?php echo stripslashes($member->city);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_state){?>
<tr><td width="30%"><?php echo JText::_( 'DT_STATE' ); ?>:</td><td width="68%"><input type="text" name="state" value="<?php echo stripslashes($member->state);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_country){?>
<?php require(JPATH_SITE."/components/com_dtregister/country.htm")?>
<?php } ?>
<?php if($m_s_zip){?>
<tr><td width="30%"><?php echo JText::_( 'DT_ZIPCODE' ); ?>:</td><td width="68%"><input type="text" name="zip" value="<?php echo stripslashes($member->zip);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_phone){?>
<tr><td width="30%"><?php echo JText::_( 'DT_PHONE' ); ?>:</td><td width="68%"><input type="text" name="phone" value="<?php echo stripslashes($member->phone);?>" /></td><td width="2%" >&nbsp;</td></tr>
<?php } ?>
<?php if($m_s_email){?>
<tr><td width="30%"><?php echo JText::_( 'DT_EMAIL' ); ?>:</td><td width="68%"><input type="text" name="email" value="<?php echo stripslashes($member->email);?>" /></td><td width="2%" >&nbsp;</td></tr>
 <?php } ?>
   
   <?php
	
   $evt->read();
   if($dt_user->userType=='G'){
       $field_type = "B";
   }else{
      $field_type = "I";
   }
   echo $evt->field_html("M",$member);
	?>
    <tr><td colspan="3" align="center">
    
     <input type="button" class="button" name="back" onclick='window.location="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=listmembers&id='.$dt_user->userId,$xhtml_url ) ?>"' value="<?php echo JText::_( 'DT_BACK' );?>" />
    &nbsp;<input type="submit" class="button" name="savenewmember" value="<?php echo JText::_( 'DT_ADDMEMBER' );?>" /></td></tr>
     <input name="id" type="hidden" value="<?php echo JRequest::getVar( 'id' ); ?>" />
     <input name="task" type="hidden" value="savenewmember" />
     <input name="option" type="hidden" value="com_dtregister" />
     <input name="Itemid" type="hidden" value="<?php echo $Itemid?>" />
     </form>
   </table>
   <?php
  
}

function cancelregisteration($option){
  global $Itemid , $mainframe;
  $dt_user  =  new DT_User(JRequest::getVar('id'));
  $totamount = $dt_user->get_amount();
  $cancel_amount = cancel_fee($totamount);
   $dt_evt = new Event($dt_user->eventId) ; 
   $cancel_amount += $dt_evt->getTaxAmount($cancel_amount);
    $dt_evt->get_cancel_amount($totamount,$dt_user->paid_amount);
	   
	$_SESSION['billinginfo']['register']['feechanges'] = $dt_evt->total_fee;
	$dt_user->cancel = 1 ;
	$dt_user->due_payment = $amount ;
	$userId = $dt_user->id;
	$_SESSION['billinginfo']['register']['user'] = serialize($dt_user);
    $_SESSION['register']['cancel_paying_amount'] = $dt_evt->paying_amount;
	 $_SESSION['billinginfo']['register']['pay_amount'] = $dt_evt->paying_amount; 
	$_SESSION['register']['set_fee'] = $dt_evt->total_fee ;
	
    $_SESSION['register']['cancel_fee'] = $dt_evt->cancel_fee ;
	
  $mainframe->redirect("index.php?option=com_dtregister&task=confirmchanges&userId=".$userId."&cancel=1&Itemid=".$Itemid);
  
}

function chgidealRaboSuccess($option){
   
   global $mainframe , $Itemid;
   $mosConfig_live_site = JURI::base( true );
   $_SESSION['register']['payment_type'] = 'ideal' ;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();
    $_SESSION['register']['payment_type'] = 'ideal';
	$_SESSION['register']['transaction_id'] = $_REQUEST['transaction_id'] ;
    saveuser('com_dtregister',1);
	
}

function chgidealRaboCancel($option){
   
   global $mainframe , $Itemid;
  
		   $msg .= '<strong>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</strong>';
	
		 echo $msg.'<p><a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'>'.JText::_( 'RETURN_TO_SITE' ).'</a></p>';
	
}

function chgidealRaboError($option){
   
   global $mainframe , $Itemid;
  
	  echo JText::_( 'DT_ERROR_PAYMENT_IDEAL' );
	
}

function savecancel($type,$status=0){
  global $Itemid ,$mainframe ;
   
  $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
  $dt_user->DT_User($dt_user->id,$dt_user->eventId);
  $amount = $_SESSION['register']['set_fee'] ;
 // $dt_user->set_amount($amount);
  
  $dt_user->save_field('cancel',1);
  if($dt_user->event->cancel_refund_status){
     $dt_user->due_payment = $amount - ($_SESSION['register']['cancel_paying_amount'] + $dt_user->paid_amount ) ;
  }else{
     $dt_user->due_payment = 0 ;
  }
  $dt_user->save_field('due_payment', $dt_user->due_payment);
	$history = array();
	if($_SESSION['register']['cancel_paying_amount'] > 0){
	
	   $dt_user->save_field('paid_amount',($_SESSION['register']['cancel_paying_amount'] + $dt_user->paid_amount ));
	
		$history = array(
				 'user_id'=>$dt_user->id,
						 'type'=>$_SESSION['register']['payment_type'],
						 'amount'=>($_SESSION['register']['cancel_paying_amount']),
						 'payment_date'=>$now->toFormat("%Y-%m-%d"),
						 'reason'=>'cancel'
				  );
		$database = &JFactory::getDBO();
	
		$row = new DThistory( $database );
		
		$row->bind( $history);
		
		$row->store( $history);
	}else{
	  
	}
	
    cancel_email($dt_user,$history,$_SESSION['register']['cancel_fee']);
	
    unset($_SESSION['billinginfo']);
	unset($_SESSION['register']);
	$mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,  JText::_( 'DT_CANCEL_SUCCESSFUL' ));
	$mainframe->redirect( "index.php?option=com_dtregister&task=cancelthk&eventId=".$dt_user->event->id."&Itemid=".$Itemid ,  JText::_( 'DT_CANCELLED' ));
}

function paypal_due_notify(){

  global $database,$Itemid,$my,$ptc;

	$database = &JFactory::getDBO();

   require_once(JPATH_SITE.'/components/com_dtregister/paypal.class.php');  // include the class file

	 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	 $p = new paypal_class; // initiate an instance of the class

	 $p->paypal_url = ($paypalmode=='test')?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url

		 $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			$sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;
  
	  if($p->validate_ipn() && ($_REQUEST['payment_status']=='Completed' || $_REQUEST['payment_status']=='Pending' || $_REQUEST['payment_status']=='Processed')){

	  	 $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			 $sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
             $_SESSION['register']['payment_type'] = 'paypal';
			 
             if($row[0]->user_id == 0){
               $userId = saveduepayment('Paypal',1);
		      $sql = "update #__dtregister_session set user_id='".$userId."' where id=".$paypal_session_id;

	         $database->setQuery($sql);

              $database->query();

          }

	 }

}

function paypal_payduefailure($option){
 
 global $Itemid,$ptc,$mainframe;
 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
 
 $mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid );
 /* $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			$sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;

$dt_user = unserialize($_SESSION['billinginfo']['register']['user']); 
 $dt_user->DT_User($dt_user->id,$dt_user->eventId);
echo str_replace('[EVENT_NAME]',$dt_user->event->summary,$upcancelmsg);*/

}

function paypal_payduereturn($option){
 global $Itemid,$ptc,$mainframe;
 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
/* $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			$sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;

$dt_user = unserialize($_SESSION['billinginfo']['register']['user']); 
  $dt_user->DT_User($dt_user->id,$dt_user->eventId);
unset($_SESSION['billinginfo']);
	unset($_SESSION['register']); */
$mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,  JText::_( 'DT_PAYMENT_SUCCESSFUL' ));
 $upthanksmsg =  str_replace( "[EVENT_NAME]",$dt_user->event->summary,$upthanksmsg) ;
   echo $upthanksmsg =  str_replace( "[EVENT_DATE]",get_date($dt_user->event->dtstart,$dt_user->event->dtend),$upthanksmsg) ;
 
}

function payduethk(){
        global $Itemid,$ptc,$mainframe;
        if(isset($_REQUEST['dtevent'])){
			  
			  $sql  = "select * from #__dtregister_session where id=".$_REQUEST['dtevent'];

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();
    
			 $data = unserialize($row[0]->data);
             $userId = $row[0]->user_id ;
			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;
			 if($userId ==  0 || $userId==""){
			       
					require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['payment_type'].'.php');

                     $payment =  new $_SESSION['register']['payment_type']();

                     $payment->afterpayment();
					 $_SESSION['register']['transaction_id'] = $payment->TransactionID ;
					 if($_SESSION['register']['paymentMethod'] !="GoogleCheckout"){
					  $userId = saveduepayment($_SESSION['register']['payment_type'],1);
						 if($row[0]->user_id == 0){
			
						  $sql = "update #__dtregister_session set user_id='".$userId."' where id=".$_REQUEST['dtevent'] ;
			
						 $database->setQuery($sql);
			
						  $database->query();
			
					  }
					 }
				}
		 }
         $mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,  JText::_( 'DT_PAYMENT_SUCCESSFUL' ));
}

function duepaymentForm($paymethod){
  
  global $Itemid,$ptc,$mainframe;
  $user = &JFactory::getUser();
  $database = &JFactory::getDBO();
  $mosConfig_live_site = JURI::root( false );
  include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
 
  $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
  $dt_user_new =  unserialize($_SESSION['billinginfo']['register']['user']);
 
   $amount = $_SESSION['register']['due_paying_amount'];
  $dt_user->DT_User($dt_user->id,$dt_user->eventId);
  $amount = str_replace(",",".",$amount);
  $billinginfo = (array)$dt_user ;
  ?>
  <div class="componentheading"> <?php echo JText::_( 'DT_MAKE_PAYMENT'); ?>: <?php echo $dt_user->event->summary; ?> (<?php echo get_date($dt_user->event->dtstart,$dt_user->event->dtend); ?>)</div>
  <?php
   $dt_user->event->over_ride_global();
    $arrCode=array(

     		'USD'=>'$',

     		'BRL'=>'R$',

     		'ZAR'=>'R',

     		'GBP'=>'&#163;',

     		'EUR'=>'&#128;',

     		'JPY'=>'&#165;'

     	);

		foreach($arrCode as $arKey=>$arValue){

			if ($arKey === $currency_code){

				$currency_symbol = $arValue;

				break;

		} else {

			$currency_symbol = NULL;

		}

		}
		if($currency_symbol !=""){
		  $dis_currency_code = $currency_code;
		}else{
		  $dis_currency_code = $currency_code ;
		}

    ?>

  <table>
    <tr>
      <td>
       <?php echo JText::_( 'DT_AMOUNT') ?>
      </td>
      <td><?php  echo $currency_symbol.numberFormat($amount,2) . ' ' . $dis_currency_code;;?>
      </td>
    </tr>
  </table>
  <?php
  switch($paymethod){
     
			 case 'idealRabo':
             
			 $urlCancel = "{$mosConfig_live_site}index.php?option=com_dtregister&task=due_payment&type=idealRaboCancel&userId=$userId&Itemid=$Itemid";
			 $urlSuccess = "{$mosConfig_live_site}index.php?option=com_dtregister&task=due_payment&type=idealRaboSuccess&userId=$userId&Itemid=$Itemid";
			 $urlError = "{$mosConfig_live_site}index.php?option=com_dtregister&task=due_payment&type=idealRaboError&userId=$userId&Itemid=$Itemid";
			 
			 include(JPATH_SITE."/components/com_dtregister/lib/ideallite.php");
			 
			 $oIdeal = new IdealLite();
			 $oIdeal->sCurrency = $currency_code ;
			 $oIdeal->setUrlCancel($urlCancel);
	         $oIdeal->setUrlSuccess($urlSuccess);
	         $oIdeal->setUrlError($urlError);
			 
			 $oIdeal->setAmount($amount);
	         $oIdeal->setOrderId(1);
	        $oIdeal->setOrderDescription($dt_user->event->summary);
			
			echo $oIdeal->createForm();
			 
			 //include("components/com_dtregister/view/payment/idealRabo.php");
              
			break ;
	 
	 case 'ideal':
	          echo '<form name="frmcart" method="post" action="index.php">' ;
			  ?>
              <table>
               <tr>
                 <td>
                    <input type="hidden" name="option" value="com_dtregister" />
                 </td>
               </tr>
              </table>
              <?php
			  $task = "due_payment" ;
		      $type = "processdueIdeal";
			  include(JPATH_SITE."/components/com_dtregister/view/payment/ideal.php");
              
			  echo "</form>";
	 break ;
     case "paypal":{
		 
		 global $Itemid ;
	   $_SESSION['register']['payment_type'] = "paypal" ;
	   require_once(JPATH_SITE.'/components/com_dtregister/paypal.class.php'); // include the class file
	    $custom ="amountCharged=$amount|";
		if($currency_code==""){$currency_code='USD';}
		$sql = "INSERT INTO #__dtregister_session (`session_id` ,`data`, `user_id`)VALUES ( ".$database->Quote(session_id()).",".$database->Quote(serialize($_SESSION)).",0)" ;

		$userId = $dt_user->userId;
		$database->setQuery($sql);
		$database->query();
		$rowid=$database->insertid();
		$custom .="userId=$userId|";
        $custom .="session=$rowid";
		$p = new paypal_class;
		$p->paypal_url = ($paypalmode=='test')?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url
        $this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        $p->add_field('business', "$paypalid");
        $p->add_field('return', "{$mosConfig_live_site}index.php?option=com_dtregister&task=due_payment&type=paypal_payduereturn&userId=$userId&amount=$amount&Itemid=$Itemid");
        $p->add_field('cancel_return', "{$mosConfig_live_site}index.php?option=com_dtregister&task=due_payment&type=paypal_payduefailure&Itemid=$Itemid&userId=$userId");
        $p->add_field('notify_url', "{$mosConfig_live_site}components/com_dtregister/paypal_due_ipn.php?amount=$amount");
        if($paypalmode=='test'){
          $p->add_field('test_ipn', 1);
        }
        $p->add_field('item_name', $dt_user_new->event->summary);
        $p->add_field('first_name', $dt_user->userFirstName);
        $p->add_field('last_name', $dt_user->userLastName);
        $p->add_field('address1', $dt_user->userAddress);
        $p->add_field('city', $dt_user->userCity);
        $p->add_field('state', $dt_user->userState);
        $p->add_field('zip', $dt_user->userZip);
        $p->add_field('amount', "$amount");
        $p->add_field('custom', "$custom");
        $p->add_field('email', $dt_user->userEmail);
        $punct = preg_quote("().-+", '/');
        $billing_info['phone'] = preg_replace("/[$punct]/", '', $dt_user->userPhone);
        $p->add_field('night_phone_a', substr($billing_info['phone'],0,3));
        $p->add_field('night_phone_b', substr($billing_info['phone'],3,3));
        $p->add_field('night_phone_c', substr($billing_info['phone'],-4));
        //add currency to the form
        $p->add_field('currency_code',$currency_code);
        $p->submit_paypal_post(); // submit the fields to paypal
      }
	 break; 
	 case "authorizenet": {
	 
	   $_SESSION['register']['payment_type'] = "authorizenet" ;
	   if($cb_integrated == 1){
         $userId=$user->id;
         if ($userId){
		   //Get the information from cb
           $sql="Select * From #__comprofiler where user_id=$userId";
           $database->setQuery($sql);
		   $rowProfile =  false ;
           if($cb_integrated==1)
           $rowProfile = $database->loadObject();
           if($rowProfile){
             //Decode some string
             global $ptc;
             $ptc->ToDecode=$rowProfile->cb_creditcardnumber;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
                $rowProfile->cb_creditcardnumber=$ptc->Decoded;
             $ptc->ToDecode=$rowProfile->cb_expdate;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
               $rowProfile->cb_expdate=$ptc->Decoded;
           }
          }
         }
		?>
        <form name="frmcart" method="post" action="index.php">
        <table>
        <?php billingform($dt_user);?>
          <tr>
            <td width="31%" ><?php echo JText::_( 'CARD_TYPE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>
              <td width="69%" align="left" ><?php
                 $cardtypearr = explode(",",$cardtype);

				  $cardType=$rowProfile->cb_cardtype;
                  if(isset($billinginfo['cardtype'])){
				  		$cardType = $billinginfo['cardtype'] ; 
				  }
				  if(isset($billinginfo['x_card_num'])){
				  	 $rowProfile->cb_creditcardnumber = $billinginfo['x_card_num'] ;
				  }
				  if(isset($billinginfo['x_card_code'])){
				  	 $x_card_code = $billinginfo['x_card_code'] ;
				  }else{
				  	$x_card_code = "";
				  }
				   if(isset($billinginfo['x_exp_date'])){
				  	 $rowProfile->cb_expdate = $billinginfo['x_exp_date'] ;
				  }
				 $size = count($cardtypearr);
				if($size==1){
				   echo $cardtypearr[0];
				   
				    ?>
                    <input type="radio" style="display:none"  name="cardtype" value="<?php echo  $cardtypearr[0];?>"  <?php  echo "checked"; ?> />
                  <?php
				   
				}
				 
				   if($size>1)
				for($i=0;$i<count($cardtypearr);$i++)

				{?>

		        <input type="radio" name="cardtype" value="<?php echo  $cardtypearr[$i];?>"  <?php if($cardtypearr[$i]==$cardType) echo "checked"; ?> /><?php echo  $cardtypearr[$i];?><br />

				<?php } ?>

		       </td>

		        </tr>

		        <tr>
                 
		          <td width="31%" ><?php echo JText::_( 'CARD_NUMBER' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		         <td width="69%" align="left" ><input type="text" name="x_card_num" onKeyUp="chknumber(this)" class="inputbox" value="<?php echo $rowProfile->cb_creditcardnumber?>" />

		              <br />

		            <?php echo JText::_( 'CARD_NUMBER_EXPLANATION' );?></td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CARD_EXPIRY_DATE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		          <td width="69%" align="left" ><input type="text" name="x_exp_date" value="<?php echo $rowProfile->cb_expdate?>" class="inputbox" />

		            &nbsp;&nbsp;(mm/yy)</td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CVV_CODE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		         <td width="69%" align="left" ><input type="text" name="x_card_code" size="10" onKeyUp="chknumber(this)" class="inputbox" value="<?php echo $x_card_code ;?>" />

		            <?php echo JText::_( 'CVV_CODE_EXPLANATION' );?></td>

		        </tr>

		        <tr>

		          <td>

                  <input type="button" onclick="window.location='<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=due_payment&back=1&id='.$dt_user->id,$xhtml_url ) ?>'" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

                  <input type="button" name="send" value="<?php echo JText::_('DT_NEXT_BUTTON'); ?>" class="button" onclick="sendPayment();" /></td>

		          <td align="left" >&nbsp;<input type="hidden" name="authPayment" value="1" /><input type="hidden" name="option" value="com_dtregister" /><input type="hidden" name="task" value="due_payment" /><input type="hidden" name="type" value="processdueAuthorizenet" /></td>

		        </tr>

		        </table>

	      </form>
		 <script language="javascript" type="text/javascript">
		 
		   //<![CDATA[
		  function chknumber(txtname){

			var num = txtname.value
           
			   if(isNaN(num)){

							alert("<?php echo JText::_( 'DT_NUMBERS_ONLY' ); ?>");

							txtname.value = "";

					    	txtname.focus();

						}

			}
			function sendPayment(){
              var form=document.frmcart;
			  
			  <?php
                        // $dt_user->userType=="I"
						if(1){

						?>

						if(form.billing_firstname.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_FIRSTNAME_ERROR' ); ?>");

							form.billing_firstname.focus();

							return ;

						}

						if(form.billing_address.value==""){

							alert ("<?php echo JText::_( 'DT_ADDRESS_ERROR' ); ?>");

							form.billing_address.focus();

							return ;

						}

						if(form.billing_city.value==""){

							alert ("<?php echo JText::_( 'DT_CITY_ERROR' ); ?>");

							form.billing_city.focus();

							return ;

						}

						if(form.billing_state.value==""){

							alert ("<?php echo JText::_( 'DT_STATE_ERROR' ); ?>");

							form.billing_state.focus();

							return ;

						}

						if(form.billing_zipcode.value==""){

							alert ("<?php echo JText::_( 'DT_ZIP_ERROR' ); ?>");

							form.billing_zipcode.focus();

							return ;

						}

						if(form.billing_email.value==""){

							alert ("<?php echo JText::_( 'DT_EMAIL_ERROR' ); ?>");

							form.billing_email.focus();

							return ;

						}

						<?php

						}

						?>
			  var checked=false;
			    
			     if(typeof form.cardtype.length =='undefined'){
						checked =true ;
						 cardType = form.cardtype.value;
				 }
			  
						for(var i=0;i<form.cardtype.length;i++){

							if(form.cardtype[i].checked==true){

								cardType = form.cardtype[i].value;

								checked=true;

								break;

							}

						}

						if(!checked){

							alert ("<?php echo JText::_( 'DT_CC_CARD_TYPE' ); ?>");

							return;

						}
						if(form.x_card_num.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_NUMBER' ); ?>");

							form.x_card_num.focus();

							return ;

						}

						if(form.x_exp_date.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_EXPIRE_DATE' ); ?>");

							form.x_exp_date.focus();

							return ;

						}

						if(form.x_card_code.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_CODE' ); ?>");

							form.x_card_code.focus();

							return ;

						}
						
					   confirmText = "<?php echo JText::_( 'DT_CONFIRM_CC_INFO' ); ?>\n\n";
					   confirmText = confirmText+"\n<?php echo JText::_( 'CARD_TYPE' ); ?>: \t "+cardType+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CARD_NUMBER' ); ?>: "+form.x_card_num.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CARD_EXPIRY_DATE' ); ?>: "+form.x_exp_date.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CVV_CODE' ); ?>:\t "+form.x_card_code.value+"\n";
						
						 confirmText = confirmText+"<?php echo JText::_( 'DT_AMOUNT' ); ?>:\t<?php echo $amount; ?>";

						var answer = confirm(confirmText);

						if (answer){
                            document.frmcart.send.disabled = true ;
							form.submit();

						}
              
			}
			//]]>
		 </script>
            <?php
	 }	
	 break ;
	 case "echeck":{
	    $_SESSION['register']['payment_type'] = "echeck" ;
	    if($cb_integrated == 1){
         $userId=$user->id;
         if ($userId){
		   //Get the information from cb
           $sql="Select * From #__comprofiler where user_id=$userId";
           $database->setQuery($sql);
		   $rowProfile =  false ;
           if($cb_integrated==1)
           $rowProfile = $database->loadObject();
           if($rowProfile){
             //Decode some string
             global $ptc;
             $ptc->ToDecode=$rowProfile->cb_creditcardnumber;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
                $rowProfile->cb_creditcardnumber=$ptc->Decoded;
             $ptc->ToDecode=$rowProfile->cb_expdate;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
               $rowProfile->cb_expdate=$ptc->Decoded;
           }
          }
         }
	   ?>
       <form name="frmcart" method="post" action="index.php">
       <table>
         <?php billingform($dt_user);?>
         <tr><td colspan="2" ><strong><?php echo JText::_( 'DT_BANK_INFORMATION' ) ?></strong><br /></td></tr>
          <tr><td><?php echo JText::_( 'DT_BANK_ROUTING_NUMBER' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

					<td><input type="text" name="x_bank_aba_code" onKeyUp="chknumber(this)" class="inputbox"  size="20" maxlength="16" value="<?php echo $rowProfile->cb_routingnumber?>"/></td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_NUMBER' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><input type="text" name="x_bank_acct_num" onKeyUp="chknumber(this)" class="inputbox"  size="20" maxlength="16" value="<?php echo $rowProfile->cb_acctnumber?>"/></td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_TYPE' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><select name="x_bank_acct_type">

			        	<option value="CHECKING" <?php echo($x_bank_acct_type=='CHECKING')?'selected':''?>><?php echo JText::_( 'DT_BANK_CHECKING' ); ?></option>

						<option value="SAVINGS" <?php echo($x_bank_acct_type=='SAVINGS')?'selected':''?>><?php echo JText::_( 'DT_BANK_SAVINGS' ); ?></option>

						</select>

			        </td></tr>
         <tr><td><?php echo JText::_( 'DT_BANK_NAME' ); ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><input type="text" name="x_bank_name" class="inputbox" size="30" value="<?php echo $rowProfile->cb_bankname?>"/></td></tr>

			  	<tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_HOLDER' ); ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td><td><input type="text" name="x_bank_acct_name" class="inputbox" size="30" value="<?php echo $rowProfile->cb_accountholder?>"/></td></tr>
	<tr><td colspan="2" align="center">&nbsp;</td></tr>

					<tr><td colspan="2" align="center">

						<input type="hidden" name="task" value="due_payment" />

						<input type="hidden" name="type" value="processdueEcheck" />
                        
                        <input type="hidden" name="option" value="com_dtregister" />

						<input type="button" onclick="window.location='<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=due_payment&back=1&id='.$dt_user->id,$xhtml_url ) ?>'" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

						<input type="button" name="send" value="<?php echo JText::_( 'DT_SEND_BUTTON' ); ?>" class="button" onclick="sendPayment();" />

					</td></tr>
                
       </table>
       </form>
       <script language="javascript">
					function chknumber(txtname){

						var num = txtname.value

					    if(isNaN(num)){

							alert("<?php echo JText::_( 'DT_NUMBERS_ONLY' ); ?>");

							txtname.value = "";

					    	txtname.focus();

						}

					}
		function sendPayment(){
		    var frm=document.frmcart;
			var form=document.frmcart;
			
			<?php

						if($_SESSION['register']['memtot']==1){

						?>

						if(form.billing_address.value==""){

							alert ("<?php echo JText::_( 'DT_ADDRESS_ERROR' ); ?>");

							form.billing_address.focus();

							return ;

						}

						if(form.billing_city.value==""){

							alert ("<?php echo JText::_( 'DT_CITY_ERROR' ); ?>");

							form.billing_city.focus();

							return ;

						}

						if(form.billing_state.value==""){

							alert ("<?php echo JText::_( 'DT_STATE_ERROR' ); ?>");

							form.billing_state.focus();

							return ;

						}

						if(form.billing_zipcode.value==""){

							alert ("<?php echo JText::_( 'DT_ZIP_ERROR' ); ?>");

							form.billing_zipcode.focus();

							return ;

						}

						if(form.billing_email.value==""){

							alert ("<?php echo JText::_( 'DT_EMAIL_ERROR' ); ?>");

							form.billing_email.focus();

							return ;

						}

						<?php

						}

						?>
if(frm.x_bank_aba_code.value==""){

								alert ("<?php echo JText::_( 'DT_BANK_ROUTING' ); ?>")

								frm.x_bank_aba_code.focus();

								return;

						}

						if(frm.x_bank_acct_num.value==""){

							alert ("<?php echo JText::_( 'DT_BANK_ACCOUNT' ); ?>")

							frm.x_bank_acct_num.focus();

							return;

						}

						if(frm.x_bank_name.value=='' || frm.x_bank_acct_name.value.charAt(0)==' '){

							  alert("<?php echo JText::_( 'DT_BANK_NAME' ); ?>");

							  frm.x_bank_name.focus();

							  return;

					  	}

						if(frm.x_bank_acct_name.value=='' || frm.x_bank_acct_name.value.charAt(0)==' '){

						  	alert("<?php echo JText::_( 'DT_BANK_USER' ); ?>");

						  	frm.x_bank_acct_name.focus();

							return;

						}

						confirmText = "<?php echo JText::_( 'DT_CONFIRM_BANK_ACCOUNT_INFO' ); ?>\n";
confirmText = confirmText+"\n<?php echo JText::_( 'DT_BANK_ROUTING_NUMBER' ); ?>:\t"+frm.x_bank_aba_code.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_NUMBER' ); ?>:\t"+frm.x_bank_acct_num.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_TYPE' ); ?>:\t\t"+frm.x_bank_acct_type.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_NAME' ); ?>:\t\t"+frm.x_bank_name.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_HOLDER' ); ?>:\t"+frm.x_bank_acct_name.value;

						var answer = confirm(confirmText);

						if (answer){

							frm.submit();

						}
		}
	   
	   </script>
       <?php
	  }
	 break; 
	 default :{
	 
			   $_SESSION['register']['payment_type'] = $paymethod ;
			  
			    require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['payment_type'].'.php');
				
			     $payment =  new $paymethod();
				
				 $dt_user->firstname = $dt_user->userFirstName;
				 $dt_user->lastname = $dt_user->userLastName;
				 $dt_user->address = $dt_user->userAddress;
				 $dt_user->city = $dt_user->userCity;
				 $dt_user->state = $dt_user->userState;
				 $dt_user->zip = $dt_user->userZip;
				 $dt_user->email = $dt_user->userEmail;
				 
				$payment->setBillinginfo((array)$dt_user);
				
				 echo '<form name="frmcart" method="post" action="index.php">' ;
				 $payment->setPaymentType('duepay');
				
				 $payment->beforepayment();
				  $data =  array(
				        'eventName'=>  $dt_user->event->summary ,
						'amount'=>$amount 
				 );
				 
				  if($_SESSION['register']['payment_type']=='GoogleCheckout')
				 echo "</form>";
				
				 $payment->setData($data);
				 $options = array('message'=>JText::_( 'DT_'.strtoupper($_SESSION['register']['payment_type']).'_REDIRECT_MSG' ));
				 echo $payment->showform( $options) ;
    
			}
  }
  
}

function processchgIdeal($option,$Itemid){
   
   global $mainframe , $Itemid ;
   $user = &JFactory::getUser();
   $database = &JFactory::getDBO();
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
    include(JPATH_SITE."/components/com_dtregister/ideal.class.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();
   $amount =  $_SESSION['billinginfo']['register']['pay_amount'] ;
    $amount = $amount*100;
    $return_url  = JUri::root().'index.php?option=com_dtregister&Itemid='.$Itemid.'&task=idealchgReturn'; // 

    $report_url  = JUri::root().'index.php?option=com_dtregister&Itemid='.$Itemid.'&task=idealchgReport'; //
	$iDEAL = new iDEAL_Payment ($partner_id);

   if($idealmode=='test'){

     $iDEAL->setTestmode();

   }
   $data = $iDEAL->createPayment($_POST['bank_id'], $amount, $dt_user->event->summary, $return_url, $report_url);

  $data = $iDEAL->getBankURL();

 $mainframe->redirect( $iDEAL->getBankURL());
  
  if($amount < 118){

    echo JText::_( 'DT_ERROR_IDEAL_MINIMUM_AMOUNT' );

  }
   
}

function idealchgReturn($option){

   global $mainframe , $Itemid;
   $mosConfig_live_site = JURI::base( true );
   $_SESSION['register']['payment_type'] = 'ideal' ;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();
    if (isset($_GET['transaction_id'])) {  
     $_SESSION['register']['billingInfo']['transaction_id'] = $_GET['transaction_id'];
    $iDEAL = new iDEAL_Payment ($partner_id);

    $iDEAL->checkPayment($_GET['transaction_id']);

		if ($iDEAL->getPaidStatus() == true) {
	
		  saveuser("com_dtregister",1);
	
		}else{
		   $msg .= '<strong>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</strong>';
	
		 echo $msg.'<p><a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'>'.JText::_( 'RETURN_TO_SITE' ).'</a></p></form>';
		}
	}
  
}

function idealchgReport($option){
   
    global $mainframe , $Itemid;

    echo JText::_( 'DT_ERROR_PAYMENT_IDEAL' );
}
function processchgNetDeposit($option, $Itemid){
   
      global $mainframe , $Itemid ;
   
   $user = &JFactory::getUser();
   $database = &JFactory::getDBO();
   $mosConfig_live_site = JURI::base( true );
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['payment_type'].'.php');
	$cardtype=JRequest::getVar("cardtype");

	$card_num=JRequest::getVar("x_card_num");

	$exp_date=JRequest::getVar("x_exp_date");

	$num=strlen($card_num);
	$cc_num="";
	for($i=0;$i<=$num-5;$i++){

		$cc_num.="x";

	}

	$cc_num.="-";

	$cc_num.=substr($card_num,$num-4,4);
	
	$dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
	$dt_user->DT_User($dt_user->id,$dt_user->eventId);
	$amount  = $_SESSION['billinginfo']['register']['pay_amount']  ;
	$cardtype=JRequest::getVar("cardtype");

	$card_num=JRequest::getVar("x_card_num");

	$exp_date=JRequest::getVar("x_exp_date");
	$dt_user->cardtype=$cardtype ;

	$dt_user->x_card_num=JRequest::getVar('x_card_num','','post') ;									

	$dt_user->x_exp_date=JRequest::getVar('x_exp_date','','post') ;	

	$dt_user->x_card_code=JRequest::getVar('x_card_code','','post') ;	
	
	 $payment =  new $_SESSION['register']['payment_type']();
	 $payment->setBillinginfo((array)$dt_user);
	 $payment->setPaymentType('duepay');
	 $payment->beforepayment();
	  $data =  array(
			'eventName'=>  $dt_user->event->summary ,
			'amount'=>$amount 
	 );
	 $payment->setData($data);
	 $status= $payment->processPayment();
	 if($status==1){
	   $_SESSION['register']['transaction_id'] = $payment->TransactionID ;
	   saveuser("com_dtregister",1); // currentnee
	   // save user info ;
	   // unset session ;
	}else{
	  		$billing_firstname=JRequest::getVar('billing_firstname','','post');

		$billing_lastname=JRequest::getVar('billing_lastname','','post');

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$dt_user->billing_firstname  = $billing_firstname;

		$dt_user->billing_lastname=$billing_lastname;

		$dt_user->billing_address=$billing_address;

		$dt_user->billing_state=$billing_state;

		$dt_user->billing_city= $billing_city;

		$dt_user->billing_zipcode=$billing_zipcode;

		$dt_user->billing_email=$billing_email ;

		$dt_user->cardtype=$cardtype ;

		$dt_user->x_card_num=JRequest::getVar('x_card_num','','post') ;									

		$dt_user->x_exp_date=JRequest::getVar('x_exp_date','','post') ;	

		$dt_user->x_card_code=JRequest::getVar('x_card_code','','post') ;	
		
		 $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;
	 ?>
     <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="paymentchanges" />

	<input type="hidden" name="type" value="<?php echo $_SESSION['register']['payment_type']; ?>" />

		<!-- Other field in bank account info-->

		<input  class="button" type="submit" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>
  
     <?php
	   
	}

}
function processchgAuthorizenet($option,$Itemid){
   global $mainframe , $Itemid ;
   
   $user = &JFactory::getUser();
   $database = &JFactory::getDBO();
   $mosConfig_live_site = JURI::base( true );
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	$cardtype=JRequest::getVar("cardtype");

	$card_num=JRequest::getVar("x_card_num");

	$exp_date=JRequest::getVar("x_exp_date");

	$num=strlen($card_num);
	$cc_num="";
	for($i=0;$i<=$num-5;$i++){

		$cc_num.="x";

	}

	$cc_num.="-";

	$cc_num.=substr($card_num,$num-4,4);
	
	$dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
	$dt_user->DT_User($dt_user->id,$dt_user->eventId);
	$amount  = $_SESSION['billinginfo']['register']['pay_amount']  ;
	
	$DEBUGGING					= 1;				# Display additional information to track down problems

    $TESTING					= 0;				# Set the testing flag so that transactions are not live

   $TESTING =($authnetmode=='test')?1:0;

   $ERROR_RETRIES				= 2;				# Number of transactions to post if soft errors occur

   $auth_net_url = ($authnetmode=='test')?"https://test.authorize.net/gateway/transact.dll":"https://secure.authorize.net/gateway/transact.dll" ;

   $t= ($TESTING)?'TRUE':'FALSE';

   $auth_net_login_id			= $merchid;

   $auth_net_tran_key			= $transkey;
   if(!isset($ses_invoiceno)){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$ses_invoiceno = "DC-".$x_invoice_num1;
		 
        $ses_invoiceno = $dt_user->generateconfirmNum();

   	}

$authnet_values				= array

(

//  ###########3  MINIMUM TRANSACTION REQUIRED DETAILS  ################3

	"x_login"				=> $auth_net_login_id,

	"x_version"				=> "3.1",

    "x_delim_char"			=> "|",

	"x_delim_data"			=> "TRUE",

	"x_url"					=> "FALSE",

	"x_type"				=> "AUTH_CAPTURE",

	"x_method"				=> "CC",

 	"x_tran_key"			=> $auth_net_tran_key,

 	"x_relay_response"		=> "FALSE",

 	"x_test_request"		=> "FALSE",

	"x_card_num"			=> $card_num,

	"x_exp_date"			=> $exp_date,

	"x_description"			=> $dt_user->event->summary,

    "x_card_code"           =>JRequest::getVar("x_card_code"),

	"x_amount"				=>  $amount,

    "x_test_request"        => $t,

//  ###########3  CUSTOMER DETAILS  ################3

	"x_first_name"			=>JRequest::getVar('billing_firstname','','post'),

	"x_last_name"			=>JRequest::getVar('billing_lastname','','post'),

	"x_company"      		=>$dt_user->userOrganization,

	"x_address"				=>JRequest::getVar('billing_address','','post'),

	"x_city"				=>JRequest::getVar('billing_city','','post'),

	"x_state"				=>JRequest::getVar('billing_state','','post'),

	"x_phone"				=>$dt_user->userPhone,

	"x_zip"					=>JRequest::getVar('billing_zipcode','','post'),

	"x_cust_id"				=>$x_invoice_num1,

	"x_email"				=>JRequest::getVar('billing_email','','post'),

//  ###########3  SHIPPING DETAILS  ################3

	"x_ship_to_first_name" 	=> $dt_user->userFirstName,

	"x_ship_to_last_name" 	=> $dt_user->userLastName,

	 "x_ship_to_address"  	=> $dt_user->userAddress,

	"x_ship_to_city" 		=> $dt_user->userCity,

	"x_ship_to_state" 		=> $dt_user->userState,

	"x_ship_to_country" 	=> $dt_user->userCountry,

	"x_ship_to_zip" 		=> $dt_user->userZip,

	"x_ship_to_phone" 		=> $dt_user->userPhone,

	"x_ship_to_email" 		=> JRequest::getVar('billing_email','','post'),

//  ###########3  MERCHANT REQUIRED DETAILS  ################3

	"x_invoice_num" 		=> $ses_invoiceno,

	"cc_number" 			=> $cc_num,

	"cc_expdate" 			=> $exp_date,

	"cc_emailid" 			=> JRequest::getVar('billing_email','','post'),

);
  $fields = "";

foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";

$ch = curl_init($auth_net_url); // URL of gateway for cURL to post to

// For GoDaddy hosting

$sql="SELECT config_value FROM  #__dtregister_config WHERE config_key='godaddy_hosting'";

$database->setQuery($sql);

$godaddy_hosting=$database->loadResult();

if($godaddy_hosting){

	curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

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

}
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_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###

$resp = curl_exec($ch); //execute post and get results

curl_close ($ch);

$res = explode('|',$resp);

if(($res[0]==1)||($t=="TRUE")){

	// echo "<br />".stripslashes($thanksmsg);

	//echo "<hr />";

}else{

	echo JText::_( 'DT_PAYMENT_DECLINED' );

	echo "<hr />"; 

	//echo $fields; // for debugging to know what is going to authorize.net

}
/*

RESPONSECODE  DESCRIPTION

1 This transaction has been approved.

2 This transaction has been declined.

3 There has been an error processing this transaction.

4 This transaction is being held for review.

*/

switch($res[0]){

	case 1:

		echo JText::_( 'DT_PAYMENT_SUCCESSFUL' ).'<br />';

		echo JText::_( 'DT_AUTHORIZATION_CODE' ).': '.$res[4].'<br />';

		echo JText::_( 'DT_AMOUNT' ).': '.$res[9].'<br />';

		echo JText::_( 'TRANS_ID' ).': '.$res[6].'<br />';

		echo JText::_( 'DT_INVOICE_NUMBER' ).': '.$res[7].'<br /><br />';

		break;

	case 2:

		if($res[2]==2 || $res[2]==4){

			echo JText::_( 'DT_PAYMENT_DECLINED' );

			echo JText::_( 'DT_REASON' ).": ",$res[3],'<br />';

		}

		break;

	case 3:

		/*

		echo "This transaction failed due to an error in application. Please notify the site administrator and provide the text that is displayed below:<br />";

		echo "Reason  :",$res[3],'<br />';

		*/

		if($TESTING){$status =1;

		}else{

			echo JText::_( 'DT_REASON' ).": ";

			switch($res[2]){

				case 5:

					echo JText::_( 'DT_AMOUNT_NOT_VALID' );

					break;

				case 6:

				case 37:

					echo JText::_( 'DT_CARD_NUMBER_INVALID' );

					break;

				case 7:

					echo JText::_( 'DT_EXP_DATE_INVALID' );

					break;

				case 11:

					echo JText::_( 'DT_DUPLICATE_TRANSACTION' );

					break;

				case 13:

					echo JText::_( 'DT_API_LOGIN_INVALID' );

					break;

				case 17:

				case 28:

					echo JText::_( 'DT_MERCHANT_NOT_CONFIGURED' );

					break;

				case 19:

				case 20:

				case 21:

				case 22:

				case 23:

				case 25:

				case 26:

				case 57:

				case 58:

				case 59:

				case 60:

				case 61:

				case 62:

				case 63:

					echo JText::_( 'DT_ERROR_OCCURRED' );

					echo '<a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'">'.JText::_( 'DT_CLICK_HERE' ).'</a>';

					break;

				case 27:

					echo JText::_( 'DT_AUTH_AVS_MISMATCH');

					break;

				case 34:

				case 35:

				case 38:

				case 43:

					echo JText::_( 'DT_AUTH_MERCH_SETUP_PROCESSOR' );

					break;

				case 49:

					echo JText::_( 'DT_AUTH_MAX_ALLOWED' );

					break;

				case 50:

					echo JText::_( 'DT_AUTH_TRANS_SETTLE_REFUNDED' );

					break;

				case 54:

					echo JText::_( 'DT_AUTH_REF_TRANS' );

					break;

				case 55:

					echo JText::_( 'DT_AUTH_SUM_CREDIT_REF_TRANS' );

					break;

				case 56:

					echo JText::_( 'DT_AUTH_ECHECK_ONLY' );

					break;

				case 66:

					echo JText::_( 'DT_AUTH_SECURITY_GUIDELINES' );

					break;

				case 68:

					echo JText::_( 'DT_AUTH_XVERSION_INVALID' );

					break;

				case 69:

					echo JText::_( 'DT_AUTH_XTYPE_INVALID' );

					break;

				case 78:

					echo JText::_( 'DT_AUTH_XCARD_FAILED' );

					break;

			}

		}

		break;

	}

	switch($res[38]){

		case 'N':

			echo JText::_( 'DT_AUTH_CC_CODE_MISMATCH' );

			break;

		case 'P':

			echo JText::_( 'DT_AUTH_CC_NOT_PROCESSED' );

			break;

		case 'S':

			echo JText::_( 'DT_AUTH_CC_CODE_NOT_PRESENT' );

			break;

		case 'U':

			echo JText::_( 'DT_AUTH_ISSUER_NOT_PROCESS' );

			break;

	}
	if(!$status)$status=$res[0];
	
	if($status==1){
	   $_SESSION['register']['transaction_id'] = $res[6] ;
	   saveuser("com_dtregister",1); // currentnee
	   // save user info ;
	   // unset session ;
	}else{
	  		$billing_firstname=JRequest::getVar('billing_firstname','','post');

		$billing_lastname=JRequest::getVar('billing_lastname','','post');

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$dt_user->billing_firstname  = $billing_firstname;

		$dt_user->billing_lastname=$billing_lastname;

		$dt_user->billing_address=$billing_address;

		$dt_user->billing_state=$billing_state;

		$dt_user->billing_city= $billing_city;

		$dt_user->billing_zipcode=$billing_zipcode;

		$dt_user->billing_email=$billing_email ;

		$dt_user->cardtype=$cardtype ;

		$dt_user->x_card_num=JRequest::getVar('x_card_num','','post') ;									

		$dt_user->x_exp_date=JRequest::getVar('x_exp_date','','post') ;	

		$dt_user->x_card_code=JRequest::getVar('x_card_code','','post') ;	
		
		 $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;
	 ?>
     <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="paymentchanges" />

	<input type="hidden" name="type" value="authorizenet" />

		<!-- Other field in bank account info-->

		<input  class="button" type="submit" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>
  
     <?php
	   
	}

}

function processdueIdeal($option,$Itemid){
   
   global $mainframe , $Itemid ;
   $user = &JFactory::getUser();
   $database = &JFactory::getDBO();
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
    include(JPATH_SITE."/components/com_dtregister/ideal.class.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();
   $amount = $_SESSION['register']['due_paying_amount'];
    $amount = $amount*100;
    $return_url  = JUri::root().'index.php?option=com_dtregister&Itemid='.$Itemid.'&task=idealdueReturn'; // 

    $report_url  = JUri::root().'index.php?option=com_dtregister&Itemid='.$Itemid.'&task=idealdueReport'; //
	$iDEAL = new iDEAL_Payment ($partner_id);

   if($idealmode=='test'){

     $iDEAL->setTestmode();

   }
   $data = $iDEAL->createPayment($_POST['bank_id'], $amount, $dt_user->event->summary, $return_url, $report_url);

  $data = $iDEAL->getBankURL();

  $mainframe->redirect( $iDEAL->getBankURL());
  
  if($amount < 118){

    echo JText::_( 'DT_ERROR_IDEAL_MINIMUM_AMOUNT' );

  }
   
}
function processdueNetDeposit($option){

   global $mainframe , $Itemid ;
   
   $user = &JFactory::getUser();
   $database = &JFactory::getDBO();
   $mosConfig_live_site = JURI::base( true );
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
    require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['payment_type'].'.php');
	$cardtype=JRequest::getVar("cardtype");

	$card_num=JRequest::getVar("x_card_num");

	$exp_date=JRequest::getVar("x_exp_date");

	$num=strlen($card_num);
	$cc_num="";
	for($i=0;$i<=$num-5;$i++){

		$cc_num.="x";

	}

	$cc_num.="-";

	$cc_num.=substr($card_num,$num-4,4);
	
	$dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
	$dt_user->DT_User($dt_user->id,$dt_user->eventId);
	$dt_user->cardtype=$cardtype ;

		$dt_user->x_card_num=JRequest::getVar('x_card_num','','post') ;									

		$dt_user->x_exp_date=JRequest::getVar('x_exp_date','','post') ;	

		$dt_user->x_card_code=JRequest::getVar('x_card_code','','post') ;	
	$amount = $_SESSION['register']['due_paying_amount'];
	
	 $payment =  new $_SESSION['register']['payment_type']();
				 $payment->setBillinginfo((array)$dt_user);
				 $payment->setPaymentType('duepay');
				 $payment->beforepayment();
				  $data =  array(
				        'eventName'=>  $dt_user->event->summary ,
						'amount'=>$amount 
				 );
				 $payment->setData($data);
				$status= $payment->processPayment();
   if($status==1){
	   // user payement made;
	  
	   $_SESSION['register']['transaction_id'] = $this->TransactionID ; 
	   saveduepayment($_SESSION['register']['payment_type'],$status);
	   // unset session ;
	}else{
	  		  		$billing_firstname=JRequest::getVar('billing_firstname','','post');

		$billing_lastname=JRequest::getVar('billing_lastname','','post');

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$dt_user->billing_firstname  = $billing_firstname;

		$dt_user->billing_lastname=$billing_lastname;

		$dt_user->billing_address=$billing_address;

		$dt_user->billing_state=$billing_state;

		$dt_user->billing_city= $billing_city;

		$dt_user->billing_zipcode=$billing_zipcode;

		$dt_user->billing_email=$billing_email ;

		$dt_user->cardtype=$cardtype ;

		$dt_user->x_card_num=JRequest::getVar('x_card_num','','post') ;									

		$dt_user->x_exp_date=JRequest::getVar('x_exp_date','','post') ;	

		$dt_user->x_card_code=JRequest::getVar('x_card_code','','post') ;	
		
		 $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;
	 ?>
     <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="due_payment" />

	<input type="hidden" name="type" value="<?php echo  $_SESSION['register']['payment_type']; ?>" />

		<!-- Other field in bank account info-->

		<input type="submit" class="button" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>
  
     <?php
	   
	}
   
}
function processdueAuthorizenet($option,$Itemid){
   global $mainframe , $Itemid ;
   
   $user = &JFactory::getUser();
   $database = &JFactory::getDBO();
   $mosConfig_live_site = JURI::base( true );
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	$cardtype=JRequest::getVar("cardtype");

	$card_num=JRequest::getVar("x_card_num");

	$exp_date=JRequest::getVar("x_exp_date");

	$num=strlen($card_num);
	$cc_num="";
	for($i=0;$i<=$num-5;$i++){

		$cc_num.="x";

	}

	$cc_num.="-";

	$cc_num.=substr($card_num,$num-4,4);
	
	$dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
	$dt_user->DT_User($dt_user->id,$dt_user->eventId);
	$amount = $_SESSION['register']['due_paying_amount'];
	
	$DEBUGGING					= 1;				# Display additional information to track down problems

    $TESTING					= 0;				# Set the testing flag so that transactions are not live

   $TESTING =($authnetmode=='test')?1:0;

   $ERROR_RETRIES				= 2;				# Number of transactions to post if soft errors occur

   $auth_net_url = ($authnetmode=='test')?"https://test.authorize.net/gateway/transact.dll":"https://secure.authorize.net/gateway/transact.dll" ;

   $t= ($TESTING)?'TRUE':'FALSE';

   $auth_net_login_id			= $merchid;

   $auth_net_tran_key			= $transkey;
   if(!isset($ses_invoiceno)){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$ses_invoiceno = "DC-".$x_invoice_num1;
		 
         $ses_invoiceno = $dt_user->generateconfirmNum();

   	}

$authnet_values				= array

(

//  ###########3  MINIMUM TRANSACTION REQUIRED DETAILS  ################3

	"x_login"				=> $auth_net_login_id,

	"x_version"				=> "3.1",

    "x_delim_char"			=> "|",

	"x_delim_data"			=> "TRUE",

	"x_url"					=> "FALSE",

	"x_type"				=> "AUTH_CAPTURE",

	"x_method"				=> "CC",

 	"x_tran_key"			=> $auth_net_tran_key,

 	"x_relay_response"		=> "FALSE",

 	"x_test_request"		=> "FALSE",

	"x_card_num"			=> $card_num,

	"x_exp_date"			=> $exp_date,

	"x_description"			=> $dt_user->event->summary,

    "x_card_code"           =>JRequest::getVar("x_card_code"),

	"x_amount"				=>  $amount,

    "x_test_request"        => $t,

//  ###########3  CUSTOMER DETAILS  ################3

	"x_first_name"			=>JRequest::getVar('billing_firstname','','post'),

	"x_last_name"			=>JRequest::getVar('billing_lastname','','post'),

	"x_company"      		=>$dt_user->userOrganization,

	"x_address"				=>JRequest::getVar('billing_address','','post'),

	"x_city"				=>JRequest::getVar('billing_city','','post'),

	"x_state"				=>JRequest::getVar('billing_state','','post'),

	"x_phone"				=>$dt_user->userPhone,

	"x_zip"					=>JRequest::getVar('billing_zipcode','','post'),

	"x_cust_id"				=>$x_invoice_num1,

	"x_email"				=>JRequest::getVar('billing_email','','post'),

//  ###########3  SHIPPING DETAILS  ################3

	"x_ship_to_first_name" 	=> $dt_user->userFirstName,

	"x_ship_to_last_name" 	=> $dt_user->userLastName,

	 "x_ship_to_address"  	=> $dt_user->userAddress,

	"x_ship_to_city" 		=> $dt_user->userCity,

	"x_ship_to_state" 		=> $dt_user->userState,

	"x_ship_to_country" 	=> $dt_user->userCountry,

	"x_ship_to_zip" 		=> $dt_user->userZip,

	"x_ship_to_phone" 		=> $dt_user->userPhone,

	"x_ship_to_email" 		=> JRequest::getVar('billing_email','','post'),

//  ###########3  MERCHANT REQUIRED DETAILS  ################3

	"x_invoice_num" 		=> $ses_invoiceno,

	"cc_number" 			=> $cc_num,

	"cc_expdate" 			=> $exp_date,

	"cc_emailid" 			=> JRequest::getVar('billing_email','','post'),

);
  $fields = "";

foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";

$ch = curl_init($auth_net_url); // URL of gateway for cURL to post to

// For GoDaddy hosting

$sql="SELECT config_value FROM  #__dtregister_config WHERE config_key='godaddy_hosting'";

$database->setQuery($sql);

$godaddy_hosting=$database->loadResult();

if($godaddy_hosting){

	curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

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

}
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_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###

$resp = curl_exec($ch); //execute post and get results

curl_close ($ch);

$res = explode('|',$resp);

if(($res[0]==1)||($t=="TRUE")){

	// echo "<br />".stripslashes($thanksmsg);

	//echo "<hr />";

}else{

	echo JText::_( 'DT_PAYMENT_DECLINED' );

	echo "<hr />";

	//echo $fields; // for debugging to know what is going to authorize.net

}
/*

RESPONSECODE  DESCRIPTION

1 This transaction has been approved.

2 This transaction has been declined.

3 There has been an error processing this transaction.

4 This transaction is being held for review.

*/

switch($res[0]){

	case 1:

		echo JText::_( 'DT_PAYMENT_SUCCESSFUL' ).'<br />';

		echo JText::_( 'DT_AUTHORIZATION_CODE' ).': '.$res[4].'<br />';

		echo JText::_( 'DT_AMOUNT' ).': '.$res[9].'<br />';

		echo JText::_( 'TRANS_ID' ).': '.$res[6].'<br />';

		echo JText::_( 'DT_INVOICE_NUMBER' ).': '.$res[7].'<br /><br />';

		break;

	case 2:

		if($res[2]==2 || $res[2]==4){

			echo JText::_( 'DT_PAYMENT_DECLINED' );

			echo JText::_( 'DT_REASON' ).": ",$res[3],'<br />';

		}

		break;

	case 3:

		/*

		echo "This transaction failed due to an error in application. Please notify the site administrator and provide the text that is displayed below:<br />";

		echo "Reason  :",$res[3],'<br />';

		*/

		if($TESTING){$status =1;

		}else{

			echo JText::_( 'DT_REASON' ).": ";

			switch($res[2]){

				case 5:

					echo JText::_( 'DT_AMOUNT_NOT_VALID' );

					break;

				case 6:

				case 37:

					echo JText::_( 'DT_CARD_NUMBER_INVALID' );

					break;

				case 7:

					echo JText::_( 'DT_EXP_DATE_INVALID' );

					break;

				case 11:

					echo JText::_( 'DT_DUPLICATE_TRANSACTION' );

					break;

				case 13:

					echo JText::_( 'DT_API_LOGIN_INVALID' );

					break;

				case 17:

				case 28:

					echo JText::_( 'DT_MERCHANT_NOT_CONFIGURED' );

					break;

				case 19:

				case 20:

				case 21:

				case 22:

				case 23:

				case 25:

				case 26:

				case 57:

				case 58:

				case 59:

				case 60:

				case 61:

				case 62:

				case 63:

					echo JText::_( 'DT_ERROR_OCCURRED' );

					echo '<a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'">'.JText::_( 'DT_CLICK_HERE' ).'</a>';

					break;

				case 27:

					echo JText::_( 'DT_AUTH_AVS_MISMATCH');

					break;

				case 34:

				case 35:

				case 38:

				case 43:

					echo JText::_( 'DT_AUTH_MERCH_SETUP_PROCESSOR' );

					break;

				case 49:

					echo JText::_( 'DT_AUTH_MAX_ALLOWED' );

					break;

				case 50:

					echo JText::_( 'DT_AUTH_TRANS_SETTLE_REFUNDED' );

					break;

				case 54:

					echo JText::_( 'DT_AUTH_REF_TRANS' );

					break;

				case 55:

					echo JText::_( 'DT_AUTH_SUM_CREDIT_REF_TRANS' );

					break;

				case 56:

					echo JText::_( 'DT_AUTH_ECHECK_ONLY' );

					break;

				case 66:

					echo JText::_( 'DT_AUTH_SECURITY_GUIDELINES' );

					break;

				case 68:

					echo JText::_( 'DT_AUTH_XVERSION_INVALID' );

					break;

				case 69:

					echo JText::_( 'DT_AUTH_XTYPE_INVALID' );

					break;

				case 78:

					echo JText::_( 'DT_AUTH_XCARD_FAILED' );

					break;

			}

		}

		break;

	}

	switch($res[38]){

		case 'N':

			echo JText::_( 'DT_AUTH_CC_CODE_MISMATCH' );

			break;

		case 'P':

			echo JText::_( 'DT_AUTH_CC_NOT_PROCESSED' );

			break;

		case 'S':

			echo JText::_( 'DT_AUTH_CC_CODE_NOT_PRESENT' );

			break;

		case 'U':

			echo JText::_( 'DT_AUTH_ISSUER_NOT_PROCESS' );

			break;

	}
	if(!$status)$status=$res[0];
	
	if($status==1){
	   // user payement made;
	   $_SESSION['register']['payment_type'] = "authorize" ;
	   saveduepayment('authorize',$status);
	   // unset session ;
	}else{
	  		  		$billing_firstname=JRequest::getVar('billing_firstname','','post');

		$billing_lastname=JRequest::getVar('billing_lastname','','post');

		$billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$dt_user->billing_firstname  = $billing_firstname;

		$dt_user->billing_lastname=$billing_lastname;

		$dt_user->billing_address=$billing_address;

		$dt_user->billing_state=$billing_state;

		$dt_user->billing_city= $billing_city;

		$dt_user->billing_zipcode=$billing_zipcode;

		$dt_user->billing_email=$billing_email ;

		$dt_user->cardtype=$cardtype ;

		$dt_user->x_card_num=JRequest::getVar('x_card_num','','post') ;									

		$dt_user->x_exp_date=JRequest::getVar('x_exp_date','','post') ;	

		$dt_user->x_card_code=JRequest::getVar('x_card_code','','post') ;	
		
		 $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;
	 ?>
     <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="due_payment" />

	<input type="hidden" name="type" value="authorizenet" />

		<!-- Other field in bank account info-->

		<input type="submit" class="button" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>
  
     <?php
	   
	}

}

function idealdueReturn($option){
   
   global $mainframe , $Itemid;
   $mosConfig_live_site = JURI::base( true );
   $_SESSION['register']['payment_type'] = 'ideal' ;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();
    if (isset($_GET['transaction_id'])) {  

    $iDEAL = new iDEAL_Payment ($partner_id);

    $iDEAL->checkPayment($_GET['transaction_id']);

		if ($iDEAL->getPaidStatus() == true) {
	
		  saveduepayment('ideal',1);
	
		}else{
		   $msg .= '<strong>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</strong>';
	
		 echo $msg.'<p><a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'>'.JText::_( 'RETURN_TO_SITE' ).'</a></p>';
		}
	}
  
}

function dueidealRaboSuccess($option){
   
   global $mainframe , $Itemid;
   $mosConfig_live_site = JURI::base( true );
   $_SESSION['register']['payment_type'] = 'ideal' ;
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();
    $_SESSION['register']['payment_type'] = 'ideal';
   $userId = saveduepayment('Paypal',1);
	
}

function dueidealRaboCancel($option){
   
   global $mainframe , $Itemid;
  
		   $msg .= '<strong>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</strong>';
	
		 echo $msg.'<p><a href="'.JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid ,$xhtml_url).'>'.JText::_( 'RETURN_TO_SITE' ).'</a></p>';
	
}

function dueidealRaboError($option){
   
   global $mainframe , $Itemid;
  
	  echo JText::_( 'DT_ERROR_PAYMENT_IDEAL' );
	
}

function idealdueReport($option){
   
    global $mainframe , $Itemid;

    echo JText::_( 'DT_ERROR_PAYMENT_IDEAL' );
}

function saveduepayment($type,$status){
   
   global $Itemid ,$mainframe , $now ;
   
      $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
     $dt_user->DT_User($dt_user->id,$dt_user->eventId);
	 $amount = $_SESSION['register']['due_paying_amount'] ;
	 $amount += $dt_user->paid_amount ;
	 $dt_user->paid_amount += $_SESSION['register']['due_paying_amount'] ;
	 $dt_user->save_field('paid_amount',$amount);
	 $_SESSION['register']['payment_type'] = $type ;
	 $history = array(
	                 'user_id'=>$dt_user->id,
					 'type'=>$_SESSION['register']['payment_type'],
					 'amount'=>$_SESSION['register']['due_paying_amount'],
					 'payment_date'=>$now->toFormat("%Y-%m-%d"),
		             'reason'=>'duepayment'
	            );
	   $database = &JFactory::getDBO();

    $row = new DThistory( $database );
	
	$row->bind( $history);
	
	$row->store();
	due_email($dt_user,$history);
	unset($_SESSION['billinginfo']);
	unset($_SESSION['register']);
	$mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,JText::_( 'DT_PAYMENT_SUCCESSFUL') );
  
}

function processdueEcheck($option, $Itemid){
  
  global $Itemid ,$mainframe ;
  $user = &JFactory::getUser();
  $database = &JFactory::getDBO();
  include("components/com_dtregister/config.dtregister.php");
 
  $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
  $dt_user->DT_User($dt_user->id,$dt_user->eventId);
  $amount = $_SESSION['register']['due_paying_amount'];
  $x_bank_acct_name = 	$database->getEscaped($_POST["x_bank_acct_name"]);

  $x_bank_name  = 		$database->getEscaped($_POST["x_bank_name"]);

  $x_bank_acct_type = 	$database->getEscaped($_POST["x_bank_acct_type"]);

  $x_bank_acct_num = 	$database->getEscaped($_POST["x_bank_acct_num"]);

  $x_bank_aba_code = 	$database->getEscaped($_POST["x_bank_aba_code"]);

  $userId=$user->id;
  if(!isset($ses_invoiceno)){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$ses_invoiceno = "DC-".$x_invoice_num1;
		 $dt_user  = new DT_User();
        $ses_invoiceno = $dt_user->generateconfirmNum();

   	}
 ?>
 <table border="0" cellpadding="3">

	<tr class="v">

		<td>
<?php
 $auth_net_login_id			= $merchid;

 $auth_net_tran_key			= $transkey;
 $authnet_values				= array

(

	"x_login"				=> $auth_net_login_id,

	"x_version"				=> "3.1",

	"x_delim_char"			=> "|",

	"x_delim_data"			=> "TRUE",

	"x_type"				=> "AUTH_CAPTURE",

	"x_method"				=> "ECHECK",

 	"x_tran_key"			=> $auth_net_tran_key,

 	"x_relay_response"		=> "FALSE",

	"x_amount"				=> $amount,

//  ###########3  CUSTOMER DETAILS  ################3

	"x_first_name"			=> stripslashes(stripslashes($x_bank_acct_name)),

	"x_last_name"			=> "",

  	"x_company"    		 	=> stripslashes(stripslashes($dt_user->userFirstName)),

	"x_address"				=> stripslashes(stripslashes(JRequest::getVar('billing_address','','post'))),

	"x_city"				=>  JRequest::getVar('billing_city','','post'),

	"x_state"				=> JRequest::getVar('billing_state','','post'),

	"x_country"				=> $dt_user->userCountry,

	"x_phone"				=> $dt_user->userPhone,

	"x_zip"					=> JRequest::getVar('billing_zipcode','','post'),

	"x_email"				=> JRequest::getVar('billing_email','','post'),

	"x_cust_id"				=>$x_invoice_num1,

//  ###########3  SHIPPING DETAILS  ################3

	"x_ship_to_first_name" 	=>stripslashes(stripslashes($dt_user->userFirstName)),

	"x_ship_to_last_name" 	=>stripslashes(stripslashes($dt_user->userLastName)),

	"x_ship_to_address"  	=> stripslashes(stripslashes($dt_user->userAddress)),

	"x_ship_to_city" 		=>$dt_user->userCity,

	"x_ship_to_state" 		=> $dt_user->userState,

	"x_ship_to_country" 	=> $dt_user->userCountry,

	"x_ship_to_zip" 		=> $dt_user->userZip,

	"x_ship_to_phone" 		=> $dt_user->userPhone,

	"x_ship_to_email" 		=> $dt_user->userEmail,

	"x_ship_to_company" 	=> stripslashes(stripslashes($dt_user->userOrganization)),

	"x_invoice_num" 		=> $ses_invoiceno,

	"x_bank_aba_code"		=> $x_bank_aba_code,

	"x_bank_acct_num"		=> $x_bank_acct_num,

	"x_bank_acct_type"		=> $x_bank_acct_type,

	"x_bank_name"			=> $x_bank_name,

	"x_bank_acct_name"		=> stripslashes(stripslashes($x_bank_acct_name)),

	"x_echeck_type"			=> "WEB",

	"x_recurring_billing"	=> "NO",

	"x_description"	=> $dt_user->event->summary

);

$fields = "";
//echo "<pre>";

//print_R($authnet_values);
foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";

if($echecknetmode == "test"){

	$ch = curl_init("https://test.authorize.net/gateway/transact.dll");

	} else {

	$ch = curl_init("https://secure.authorize.net/gateway/transact.dll");

	}

if($godaddy_hosting){

	curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

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

}

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_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###

$resp = curl_exec($ch); //execute post and get results

curl_close ($ch);
echo "<hr />";

$text = $resp;

$res = explode('|',$resp);

switch($res[0]){

case 1:

			echo "<b>".JText::_( 'DT_PAYMENT_SUCCESSFUL' )."</b><br />";

			echo 'Amount: ',$res[9],'<br />';

break;

case 2:

if($res[2]==2 || $res[2]==4){

echo "<b>".JText::_( 'DT_PAYMENT_DECLINED' )."</b>";

echo DT_REASON .": ",$res[3];

}

break;

case 3:

echo "<b>". JText::_( 'DT_ECHECK_PAYMENT_FAILED' ) ."</b><br />";

echo JText::_('DT_REASON') .": ",$res[3],'<br />';

break;

default:

echo "<b>".JText::_( 'DT_ERROR' )."</b><br />";

echo $res[3] . '<br />';

break;

echo "<hr />";

///////////////////////////////////////////////

}

?>

		</td>

	</tr>

</table>

<?php

echo "<hr />";

if($res[0]==1){
$_SESSION['register']['payment_type'] = "echeck" ;
saveduepayment('echeck',1);

	$transactionid = $res[6];
	$transactionid = $ses_invoiceno ;
	// save the individual or group info
    // save  user
	//$user_id = saveInfo('E-Check (Authorize.net)', 1, $transactionid);

} else {
     $billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$dt->user->billing_address=$billing_address;

		$dt->user->billing_state=$billing_state;

		$dt->user->billing_city= $billing_city;

		$dt->user->billing_city=$billing_city;

		$dt->user->billing_email=$billing_email ;
		
		 $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;
 
    ?>
   <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="due_payment" />

	<input type="hidden" name="type" value="echeck" />

		<input type="hidden" name="x_bank_acct_name" value="<?php echo $x_bank_acct_name?>" />

		<input type="hidden" name="x_bank_name" value="<?php echo $x_bank_name?>" />

		<input type="hidden" name="x_bank_acct_type" value="<?php echo $x_bank_acct_type?>" />

		<input type="hidden" name="x_bank_acct_num" value="<?php echo $x_bank_acct_num?>" />

		<input type="hidden" name="x_bank_aba_code" value="<?php echo $x_bank_aba_code?>" />

		<!-- Other field in bank account info-->

		<input class="button" type="submit" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>
 
    <?php
}

?>
 <?php
  
}
function paychangesopts($option){
   global $Itemid ,$mainframe;
   $database = &JFactory::getDBO();
   $mosConfig_live_site = JURI::base( true );
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
   $dt_user->DT_User($dt_user->id,$dt_user->eventId);
   $dt_user->event->over_ride_global();

   $arrPaymentMethods=explode(",",$paymentmethod);
   
   if (count(array_filter($arrPaymentMethods)) == 1){

		// need to stay here if it's a pay later option - need to select the option

		if(!in_array("pay_later",$arrPaymentMethods)){

		// redirect to that payment option

			if (!headers_sent()) {

				$mainframe->redirect( $mosConfig_live_site.'/index.php?option=com_dtregister&task=paymentchanges&type='.$arrPaymentMethods[0].'&Itemid='.$Itemid);

			}

		}

	}
	if(isset($_SESSION['register']['cancel_fee'] )){
	  $toplabel = JText::_( 'DT_CANCELLATION' ) ;
	}else{
	   $toplabel = JText::_( 'DT_EDIT_RECORD' ) ;
	}
	?>
     <div class="componentheading"><?php echo $toplabel;?>: <?php echo $dt_user->event->summary; ?></div>
    <form action="index.php" name="frmcart" method="post" >
	<div id="paymentselection">

	<br />

	<?php echo JText::_( 'SELECT_PAYMENT_OPTION' );?>
   
	<table class="message">

		<?php

		if(in_array("authorizenet",$arrPaymentMethods)){?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/images/card_pay.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod1" name="paymentmethod" value="authorizenet" checked="checked" /><?php echo JText::_( 'AUTH_NET' );?>

			</td>

		</tr>

		<?php  }

		if(in_array("paypal",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/images/paypal_pay.jpg" width="149" height="100" align="middle" alt=" " />
             </td>
             <td valign="top">
				<input type="radio" id="paymentmethod2" name="paymentmethod" value="paypal" /><?php echo JText::_( 'PAYPAL' );?>

			</td>

		</tr>

		<?php }

		if(in_array("echeck",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="components/com_dtregister/assets/images/echeck_pay.jpg" width="149" height="100" align="middle" alt=" "/>
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod3" name="paymentmethod" value="echeck" /><?php echo JText::_( 'ECHECK' );?>

			</td>

		</tr>

		<?php }
       
		 if(in_array("ideal",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/ideal_pay.jpg" width="149" height="100" align="middle" alt="" />
           </td>
           <td valign="top">
				<input type="radio" id="paymentmethod4" name="paymentmethod" value="ideal" /><?php echo JText::_( 'DT_IDEAL' );?>

			</td>

		</tr>

		<?php }
		  
            if(in_array("idealRabo",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/ideal_pay.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod5" name="paymentmethod" value="idealRabo" /><?php echo JText::_( 'DT_IDEAL' );?>

			</td>

		</tr>

		<?php } 
        ?>
         <?php
            if(in_array("GoogleCheckout",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="https://checkout.google.com/buttons/checkout.gif?merchant_id=<?php echo $googlemerchid ;?><?php echo $amp;?>w=160<?php echo $amp;?>h=43<?php echo $amp;?>style=trans<?php echo $amp;?>variant=text<?php echo $amp;?>loc=en_US"  align="middle" alt="" />
           </td>
           <td valign="top">
				<input type="radio" id="paymentmethod6" name="paymentmethod" value="GoogleCheckout" /><?php echo JText::_( 'DT_GOOGLE_CHECKOUT' );?>

			</td>

		</tr>

		<?php } ?>
         <?php
            if(in_array("NetDeposit",$arrPaymentMethods)){ ?>

		<tr>

			 <td valign="top" width="164">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/card_pay.jpg" alt="" width="149" height="100" align="middle" />
			</td>
           <td valign="top">
				<input type="radio" id="paymentmethod6" name="paymentmethod" value="NetDeposit" /><?php echo JText::_( 'DT_NETDEPOSIT' );?>

			</td>

		</tr>

		<?php } ?>
        <?php
		if(0){ 
		
		?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/images/pay_later.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod7" name="paymentmethod" value="pay_later"<?php if (count($arrPaymentMethods) == 1){echo 'checked="checked"';} ?>><?php echo JText::_( 'DT_PAY_LATER' );?>

				<?php

					$options=array();

					$options[]=JHTML::_('select.option',0, JText::_( 'DT_SELECT_PAY_OPTIONS' ));

					$arrSelected=explode(",",$pay_later_options);

					if(in_array(1,$arrSelected)){

						$options[]=JHTML::_('select.option',1, JText::_( 'DT_PAY_AT_DOOR' ));

					}

					if(in_array(2,$arrSelected)){

						$options[]=JHTML::_('select.option',2, JText::_( 'DT_MAILIN_PAYMENT' ));

					}

					if(in_array(3,$arrSelected)){

						$options[]=JHTML::_('select.option',3, JText::_( 'DT_CALLIN_PAYMENT' ));

					}

					echo JHTML::_('select.genericlist', $options,'pay_later_option','','value','text');

				?>

			</td>

		</tr>

		<?php

		}
		?>

	<tr><td>

	<?php // Here is a hidden radio button. It is needed because if only a single radio button is present the JS loop below doesn't know it's selected 
	  $cancel  = "" ;
	  if(isset($_SESSION['register']['cancel_fee'])){
	     $cancel = "&cancel=1&back=1";
	  }
	?>
      
	<input type="radio" id="paymentmethod8" name="paymentmethod" value="" style="display: none;" />
   <input type="button" value="<?php echo JText::_( 'DT_BACK' ); ?>" class="button" name="backbutton" onclick='window.location="<?php echo JRoute::_('index.php?option=com_dtregister&task=confirmchanges&userId='.$dt_user->id.'&Itemid='.$Itemid.$cancel,$xhtml_url)?>"' />&nbsp;&nbsp;
	<input type="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' ); ?>" class="button" name="submitbtn" onclick="paymentform();" /></td></tr>

	</table>

</div>

	<input type="hidden" name="task" value="" />
  <input type="hidden" name="type" value="" />
	</form>

	<script type="text/javascript">
	//<![CDATA[
	
	<?php

		/* check that a payment option has been selected and redirect accordingly	*/

	?>
     function backToPrePage(){

			var form=document.frmcart;

			form.task.value="event_register";

			<?php if ($_SESSION['register']['memtot'] > 1){ ?>

				form.type.value="reg_info_check";

			<?php } else { ?>

				form.type.value="reg_info_check";

			<?php } ?>

			form.submit();

		 }
	function paymentform(){

	 	var paymentMethod="";

	 	var live_site="<?php echo $mosConfig_live_site; ?>";

	 	var Itemid="<?php echo $Itemid; ?>";

	 	// Get payment method now

		for (i=0;i<document.frmcart.paymentmethod.length;i++){

 			if (document.frmcart.paymentmethod[i].checked==true) {

           	var paymentMethod = document.frmcart.paymentmethod[i].value;

         		break;

        	}

    	}

    	<?php

//    		if (count($arrPaymentMethods) == 1){

//    			if(in_array("pay_later",$arrPaymentMethods)){

//    				echo 'paymentMethod="pay_later;"';

//    			}

//    		}

    		?>

		if(paymentMethod==""){

			alert("<?php echo JText::_( 'DT_SELECT_PAY_OPTIONS' ); ?>");

		 	return;

		}

	 	switch(paymentMethod){
            
		    case "NetDeposit":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=NetDeposit&Itemid=<?php echo $Itemid ?>";

		 	break;
			
           case "GoogleCheckout":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=GoogleCheckout&Itemid=<?php echo $Itemid ?>";

		 	break;
			
	 		case "authorizenet":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=authorizenet&Itemid=<?php echo $Itemid?>";

		 		break;

		 	case "paypal":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=paypal&Itemid=<?php echo $Itemid?>";

		 		break;

		 	case "echeck":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=echeck&Itemid=<?php echo $Itemid?>";

		 		break;
            case "ideal":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=ideal&Itemid=<?php echo $Itemid?>";

		 		break;
			   case "idealRabo":

			redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=idealRabo&Itemid=<?php echo $Itemid ?>";

			break;
		 	case "pay_later":

				payLaterOption=document.frmcart.pay_later_option.value;

		 		if(payLaterOption==0){

		 			alert("<?php echo JText::_( 'DT_SELECT_PAY_LATER_OPTION' ); ?>");

		 			return;

		 		}

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=paymentchanges&type=pay_later&pay_later_option="+payLaterOption;

		 		break;

		 	default:

		 		// alert("<?php echo JText::_( 'DT_SELECT_PAYMENT_METHOD' ); ?>");

		 		break;

		}

		redirectUrl=redirectUrl + "&Itemid=<?php echo $Itemid;?>";

	 	location.href=redirectUrl;

	 }

	//]]>
    </script>

	<?php

}
function paydueopts($option){
   
   global $Itemid ,$mainframe;
   $database = &JFactory::getDBO();
   $mosConfig_live_site = JURI::base( true );
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
  
   $dt_user = new DT_User(JRequest::getVar('id') );
    $dt_user->event->over_ride_global();
	 $arrPaymentMethods=explode(",",$paymentmethod);
   $_SESSION['billinginfo']['register']['user'] = serialize($dt_user);
   if (count(array_filter($arrPaymentMethods)) == 1){

		// need to stay here if it's a pay later option - need to select the option

		if(!in_array("pay_later",$arrPaymentMethods)){

		// redirect to that payment option

			if (!headers_sent()) {

				$mainframe->redirect( $mosConfig_live_site.'/index.php?option=com_dtregister&task=due_payment&type='.$arrPaymentMethods[0].'&Itemid='.$Itemid);

			}

		}

	}
	?>
    <div class="componentheading"> <?php echo JText::_( 'DT_MAKE_PAYMENT'); ?>: <?php echo $dt_user->event->summary; ?> (<?php echo get_date($dt_user->event->dtstart,$dt_user->event->dtend); ?>)</div>
    <form action="index.php" name="frmcart" method="post" >
	<div id="paymentselection">

	<br />

	<?php echo JText::_( 'SELECT_PAYMENT_OPTION' );?>
   
	<table class="message">

		<?php

		//Authorize.net payment method

		if(in_array("authorizenet",$arrPaymentMethods)){?>

		<tr> 
            <td valign="top">

				<img src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/images/card_pay.jpg" width="149" height="100" align="middle" alt="" />

			</td>
             <td valign="top" ><input type="radio" id="paymentmethod1" name="paymentmethod" value="authorizenet" checked="checked" /><?php echo JText::_( 'AUTH_NET' );?></td>
           </tr>

		<?php  }

		if(in_array("paypal",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/images/paypal_pay.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod"2 name="paymentmethod" value="paypal" /><?php echo JText::_( 'PAYPAL' );?>

			</td>

		</tr>

		<?php }

		if(in_array("echeck",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true) ?>/components/com_dtregister/assets/images/echeck_pay.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod3" name="paymentmethod" value="echeck" /><?php echo JText::_( 'ECHECK' );?>

			</td>

		</tr>

		<?php }
        
		if(in_array("ideal",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/ideal_pay.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod4" name="paymentmethod" value="ideal" /><?php echo JText::_( 'DT_IDEAL' );?>

			</td>

		</tr>

		<?php }
		
            if(in_array("idealRabo",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/ideal_pay.jpg" width="149" height="100" align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod5" name="paymentmethod" value="idealRabo" /><?php echo JText::_( 'DT_IDEAL' );?>

			</td>

		</tr>

		<?php } 
		
		?>
         <?php
            if(in_array("GoogleCheckout",$arrPaymentMethods)){ ?>

		<tr>

			<td valign="top">

				<img src="https://checkout.google.com/buttons/checkout.gif?merchant_id=<?php echo $googlemerchid ;?><?php echo $amp;?>w=160<?php echo $amp;?>h=43<?php echo $amp;?>style=trans<?php echo $amp;?>variant=text<?php echo $amp;?>loc=en_US"  align="middle" alt="" />
            </td>
            <td valign="top">
				<input type="radio" id="paymentmethod6" name="paymentmethod" value="GoogleCheckout" /><?php echo JText::_( 'DT_GOOGLE_CHECKOUT' );?>

			</td>

		</tr>

		<?php } ?>
        
         <?php
            if(in_array("NetDeposit",$arrPaymentMethods)){ ?>

		<tr>

			 <td valign="top" width="164">

				<img src="<?php echo JURI::root(true);?>/components/com_dtregister/assets/images/card_pay.jpg" alt="" width="149" height="100" align="middle" />
			</td>
            <td valign="top">
				<input type="radio" id="paymentmethod6" name="paymentmethod" value="NetDeposit" /><?php echo JText::_( 'DT_NETDEPOSIT' );?>

			</td>

		</tr>

		<?php } ?>
        
	<tr><td>

	<?php // Here is a hidden radio button. It is needed because if only a single radio button is present the JS loop below doesn't know it's selected ?>

	<input type="radio" id="paymentmethod7" name="paymentmethod" value="" style="display: none;" />

	<input type="button" onclick="window.location='<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=confirmpay&back=1&id='.$dt_user->id,$xhtml_url ); ?>'" class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

	<input type="button" value="<?php echo JText::_( 'DT_NEXT_BUTTON' ); ?>"  class="button" name="submitbtn" onclick="paymentform();" /></td></tr>

	</table>

</div>

	<input type="hidden" name="task" value="" />
    <input type="hidden" name="type" value="" />
	</form>

	<script type="text/javascript">
    //<![CDATA[
	<?php

		/* check that a payment option has been selected and redirect accordingly	*/

	?>
     function backToPrePage(){

			var form=document.frmcart;

			form.task.value="confirmpay";

			form.submit();

		 }
	function paymentform(){

	 	var paymentMethod="";

	 	var live_site="<?php echo $mosConfig_live_site; ?>";

	 	var Itemid="<?php echo $Itemid; ?>";

	 	// Get payment method now

		for (i=0;i<document.frmcart.paymentmethod.length;i++){

 			if (document.frmcart.paymentmethod[i].checked==true) {

           	var paymentMethod = document.frmcart.paymentmethod[i].value;

         		break;

        	}

    	}

    	<?php

//    		if (count($arrPaymentMethods) == 1){

//    			if(in_array("pay_later",$arrPaymentMethods)){

//    				echo 'paymentMethod="pay_later;"';

//    			}

//    		}

    		?>

		if(paymentMethod==""){

			alert("<?php echo JText::_( 'DT_SELECT_PAY_OPTIONS' ); ?>");

		 	return;

		}

	 	switch(paymentMethod){
            
			 case "NetDeposit":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=NetDeposit&Itemid=<?php echo $Itemid ?>";

		 		break;
			
			 case "GoogleCheckout":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=GoogleCheckout&Itemid=<?php echo $Itemid ?>";

		 		break;
			
	 		case "authorizenet":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=authorizenet&Itemid=<?php echo $Itemid?>";

		 		break;

		 	case "paypal":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=paypal&Itemid=<?php echo $Itemid?>";

		 		break;

		 	case "echeck":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=echeck&Itemid=<?php echo $Itemid?>";

		 		break;
            case "ideal":

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=ideal&Itemid=<?php echo $Itemid?>";

		 		break;
			case "idealRabo":

			redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=idealRabo&Itemid=<?php echo $Itemid ?>";

			break;
		 	case "pay_later":

				payLaterOption=document.frmcart.pay_later_option.value;

		 		if(payLaterOption==0){

		 			alert("<?php echo JText::_( 'DT_SELECT_PAY_LATER_OPTION' ); ?>");

		 			return;

		 		}

		 		redirectUrl=live_site+"/index.php?option=com_dtregister&task=due_payment&type=pay_later&Itemid=<?php echo $Itemid?>&pay_later_option="+payLaterOption;

		 		break;

		 	default:

		 		// alert("<?php echo JText::_( 'DT_SELECT_PAYMENT_METHOD' ); ?>");

		 		break;

		}

		redirectUrl=redirectUrl + "&Itemid=<?php echo $Itemid;?>";

	 	location.href=redirectUrl;

	 }

	//]]>
    </script>

	<?php

}

function paypal_chg_notify(){

  global $database,$Itemid,$my,$ptc;

	$database = &JFactory::getDBO();
	
   require_once(JPATH_SITE.'/components/com_dtregister/paypal.class.php'); // include the class file

	 include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

	 $p = new paypal_class; // initiate an instance of the class

	// $paypalmode = 'test';

	 $p->paypal_url = ($paypalmode=='test')?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url

       	//$database->query($query);

		//@ob_clean();
		 $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			$sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;
  
	  if($p->validate_ipn() && ($_REQUEST['payment_status']=='Completed' || $_REQUEST['payment_status']=='Pending' || $_REQUEST['payment_status']=='Processed')){

	  	 $data = explode('|',$_REQUEST['custom']);

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

				if(substr($value,0,7)=='session'){

					$arr = explode("=",$value);

					$paypal_session_id = $arr[1];

					break;

				}

			}

			 $sql  = "select * from #__dtregister_session where id=$paypal_session_id";

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
             $_SESSION['register']['transaction_id'] = $_REQUEST['txn_id'] ;
			 $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
			 if($row[0]->user_id == 0){
	              $userId = saveuser('com_dtregister',1);
				  $sql = "update #__dtregister_session set user_id='".$userId."' where id=".$paypal_session_id;
	
				  $database->setQuery($sql);
	
				  $database->query();
	
			  }
			 
	 }

}

function billingform($dt_user ){
 
                if(1){ // $dt_user->userType=="I" 

				?>

		        <tr><td colspan="2" ><strong><?php echo JText::_( 'DT_PAYMENT_INFORMATION' );?></strong></td></tr>

                <tr><td colspan="2" >&nbsp;</td></tr>

                <tr>

                	<td><?php echo JText::_( 'DT_SAME_BILLING_INFO' );?></td>

                	<td><input type="checkbox" class="inputbox" name="same" id="same" value="1" /></td>

                </tr>

		        <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CARD_HOLDER_FIRSTNAME' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_firstname"  class="inputbox" type="text" name="billing_firstname" value="<?php echo isset($dt_user->billing_firstname)?$dt_user->billing_firstname:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CARD_HOLDER_LASTNAME' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_lastname" class="inputbox" type="text" name="billing_lastname" value="<?php echo isset($dt_user->billing_lastname)?$dt_user->billing_lastname:'' ?>" /> </td>

                 </tr>

                   <tr>

                	<td width="31%"  ><?php echo JText::_( 'DT_BILLING_ADDRESS' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_address" class="inputbox" type="text" name="billing_address" value="<?php echo isset($dt_user->billing_address)?$dt_user->billing_address:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_CITY' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" ><input id="billing_city" class="inputbox" type="text" name="billing_city" value="<?php echo isset($dt_user->billing_city)?$dt_user->billing_city:'' ?>" />  </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_STATE' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input  id="billing_state" class="inputbox" type="text" name="billing_state" value="<?php echo isset($dt_user->billing_state)?$dt_user->billing_state:'' ?>" /> </td>

                 </tr>

                  <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_ZIPCODE' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_zipcode" class="inputbox" type="text" name="billing_zipcode" value="<?php echo isset($dt_user->billing_zipcode)?$dt_user->billing_zipcode:'' ?>" /> </td>

                 </tr>

                   <tr >

                	<td width="31%"  ><?php echo JText::_( 'DT_EMAIL' ); ?>:<span class="required">  *  </span></td>

                    <td width="69%" align="left" > <input id="billing_email" class="inputbox" type="text" name="billing_email" value="<?php echo isset($dt_user->billing_email)?$dt_user->billing_email:'' ?>" /> </td>

                 </tr>

                <script src="<?php echo Juri::root();  ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>

				<script language="javascript" type="text/javascript">
                    //<![CDATA[
					//jQuery.noConflict();
                    var billing_firstname = "<?php echo $dt_user->userFirstName ; ?>";

					var billing_lastname = "<?php echo $dt_user->userLastName; ?>";

					var billing_address = "<?php echo $dt_user->userAddress; ?>";

					var billing_city = "<?php echo $dt_user->userCity; ?>";

					var billing_state = "<?php echo $dt_user->userState; ?>";

					var billing_zipcode = "<?php echo $dt_user->userZip; ?>";

					var billing_email = "<?php echo $dt_user->userEmail; ?>";
					DTjQuery(function(){

						DTjQuery("#same").click(function(){

							if(this.checked){

								DTjQuery("#billing_firstname").val(billing_firstname);

								DTjQuery("#billing_lastname").val(billing_lastname);

								DTjQuery("#billing_address").val(billing_address);

								DTjQuery("#billing_city").val(billing_city);

								DTjQuery("#billing_state").val(billing_state);

								DTjQuery("#billing_zipcode").val(billing_zipcode);

								DTjQuery("#billing_email").val(billing_email);

							}else{

								DTjQuery("#billing_firstname").val('');

								DTjQuery("#billing_lastname").val('');

								DTjQuery("#billing_address").val('');

								DTjQuery("#billing_city").val('');

								DTjQuery("#billing_state").val('');

								DTjQuery("#billing_zipcode").val('');

								DTjQuery("#billing_email").val('');

							}

						});

					});

                     //]]>
                   </script>

                <?php 

				}else{

				$billinginfo = $_SESSION['register']['billingInfo'] ;

				?>

          <input id="billing_firstname" type="hidden" name="billing_firstname" value="<?php echo isset($dt_user->userFirstName)?$dt_user->userFirstName :'' ?>" /> 

         <input id="billing_lastname" type="hidden" name="billing_lastname" value="<?php echo isset($dt_user->userLastName)?$dt_user->userLastName :'' ?>" /> 

            <input id="billing_address" type="hidden" name="billing_address" value="<?php echo isset($dt_user->userAddress )?$dt_user->userAddress :'' ?>" /> 

             <input id="billing_city" type="hidden" name="billing_city" value="<?php echo isset($dt_user->userCity )?$dt_user->userCity :'' ?>" /> 

<input  id="billing_state"type="hidden" name="billing_state" value="<?php echo isset($dt_user->userState )?$dt_user->userState :'' ?>" /> 

<input id="billing_zipcode" type="hidden" name="billing_zipcode" value="<?php echo isset($dt_user->userZip )?$dt_user->userZip :'' ?>" />  

<input id="billing_email" type="hidden" name="billing_email" value="<?php echo isset($dt_user->userEmail )?$dt_user->userEmail :'' ?>" /> 

                <?php

				}

}

function paymentForm($paymethod){
  
  global $Itemid,$ptc,$mainframe;
  if(isset($_SESSION['register']['cancel_fee'] )){
     $toplabel = JText::_( 'DT_CANCELLATION' ) ;
  }else{
     $toplabel = JText::_( 'DT_EDIT_RECORD' )  ;
  }
  $user = &JFactory::getUser();
  $database = &JFactory::getDBO();
  $mosConfig_live_site = JURI::root( false );
  include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
  $amount =  $_SESSION['billinginfo']['register']['feechanges'];
  
  $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);

  $dt_user->DT_User($dt_user->id,$dt_user->eventId);
  
  $amount  = str_replace(",",".",$_SESSION['billinginfo']['register']['pay_amount']) ;
  $billinginfo = $_SESSION['register']['billingInfo'] ;
  if(isset($_SESSION['register']['cancel_fee'])){
     
	 $return_url = "{$mosConfig_live_site}index.php?option=com_dtregister&eventId=".$dt_user->eventId."&task=cancelthk&Itemid=".$Itemid ;
	 
  }else{
      $return_url = "{$mosConfig_live_site}index.php?option=com_dtregister&task=paymentchanges&eventId=".$dt_user->eventId."&type=paypal_paychgreturn&userId=$userId&amount=$amount&Itemid=$Itemid";
  }
  ?>
  <div class="componentheading"><?php echo $toplabel;?>: <?php echo $dt_user->event->summary; ?></div>
  <?php
  switch($paymethod){
     
	 	 case 'idealRabo':
             
			 $urlCancel = "{$mosConfig_live_site}index.php?option=com_dtregister&task=paymentchanges&type=idealRaboCancel&userId=$userId&Itemid=$Itemid";
			 $urlSuccess = "{$mosConfig_live_site}index.php?option=com_dtregister&task=paymentchanges&type=idealRaboSuccess&userId=$userId&Itemid=$Itemid";
			 $urlError = "{$mosConfig_live_site}index.php?option=com_dtregister&task=paymentchanges&type=idealRaboError&userId=$userId&Itemid=$Itemid";
			 
			 include(JPATH_SITE."/components/com_dtregister/lib/ideallite.php");
			 
			 $oIdeal = new IdealLite();
			 $oIdeal->sCurrency = $currency_code ;
			 $oIdeal->setUrlCancel($urlCancel);
	         $oIdeal->setUrlSuccess($urlSuccess);
	         $oIdeal->setUrlError($urlError);
			 
			 $oIdeal->setAmount($amount);
	         $oIdeal->setOrderId(1);
	        $oIdeal->setOrderDescription($evt->summary);
			
			echo $oIdeal->createForm();
			 
			 //include("components/com_dtregister/view/payment/idealRabo.php");
              
			break ;
	  case 'ideal':
	          echo '<form name="frmcart" method="post" action="index.php">' ;
			  ?>
              <table>
               <tr>
                 <td>
                    <input type="hidden" name="option" value="com_dtregister" />
                 </td>
               </tr>
              </table>
              <?
			  $task = "paymentchanges" ;
		      $type = "processchgIdeal";
			  include(JPATH_SITE."/components/com_dtregister/view/payment/ideal.php");
              
			  echo "</form>";
	 break ;
	 
     case "paypal":
	 $_SESSION['register']['payment_type'] = "paypal" ;
	   require_once(JPATH_SITE.'/components/com_dtregister/paypal.class.php'); // include the class file
	    $custom ="amountCharged=$amount|";
		if($currency_code==""){$currency_code='USD';}
		 $sql = "INSERT INTO #__dtregister_session (`session_id` ,`data`, `user_id`)VALUES ( ".$database->Quote(session_id()).",".$database->Quote(serialize($_SESSION)).",0)" ;
		$userId = $dt_user->userId;
		$database->setQuery($sql);
		$database->query();
		$rowid=$database->insertid();
		$custom .="userId=$userId|";
        $custom .="session=$rowid";
		$p = new paypal_class;
		$p->paypal_url = ($paypalmode=='test')?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url
        $this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        $p->add_field('business', "$paypalid");
        $p->add_field('return', $return_url);
        $p->add_field('cancel_return', "{$mosConfig_live_site}index.php?option=com_dtregister&task=paymentchanges&type=paypal_paychgfailure&Itemid=$Itemid&userId=$userId");
        $p->add_field('notify_url', "{$mosConfig_live_site}components/com_dtregister/paypal_ipn.php?amount=$amount&type=paymentchange");
        if($paypalmode=='test'){
          $p->add_field('test_ipn', 1);
        }
        $p->add_field('item_name', $dt_user->event->summary);
        $p->add_field('first_name', $dt_user->userFirstName);
        $p->add_field('last_name', $dt_user->userLastName);
        $p->add_field('address1', $dt_user->userAddress);
        $p->add_field('city', $dt_user->userCity);
        $p->add_field('state', $dt_user->userState);
        $p->add_field('zip', $dt_user->userZip);
        $p->add_field('amount', "$amount");
        $p->add_field('custom', "$custom");
        $p->add_field('email', $dt_user->userEmail);
        $punct = preg_quote("().-+", '/');
        $billing_info['phone'] = preg_replace("/[$punct]/", '', $dt_user->userPhone);
        $p->add_field('night_phone_a', substr($billing_info['phone'],0,3));
        $p->add_field('night_phone_b', substr($billing_info['phone'],3,3));
        $p->add_field('night_phone_c', substr($billing_info['phone'],-4));
        //add currency to the form
        $p->add_field('currency_code',$currency_code);
        $p->submit_paypal_post(); // submit the fields to paypal

	 break; 
	 case "authorizenet":
	   $_SESSION['register']['payment_type'] = "authorizenet" ;
	   if($cb_integrated == 1){
         $userId=$user->id;
         if ($userId){
		   //Get the information from cb
           $sql="Select * From #__comprofiler where user_id=$userId";
           $database->setQuery($sql);
		   $rowProfile =  false ;
           if($cb_integrated==1)
           $rowProfile = $database->loadObject();
           if($rowProfile){
             //Decode some string
             global $ptc;
             $ptc->ToDecode=$rowProfile->cb_creditcardnumber;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
                $rowProfile->cb_creditcardnumber=$ptc->Decoded;
             $ptc->ToDecode=$rowProfile->cb_expdate;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
               $rowProfile->cb_expdate=$ptc->Decoded;
           }
          }
         }
		?>
        <form name="frmcart" method="post" action="index.php">
        <table>
         <?php  billingform($dt_user); ?>
          <tr>
            <td width="31%" ><?php echo JText::_( 'CARD_TYPE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>
              <td width="69%" align="left" ><?php
                 $cardtypearr = explode(",",$cardtype);

				  $cardType=$rowProfile->cb_cardtype;
                  if(isset($billinginfo['cardtype'])){
				  		$cardType = $billinginfo['cardtype'] ; 
				  }
				  if(isset($billinginfo['x_card_num'])){
				  	 $rowProfile->cb_creditcardnumber = $billinginfo['x_card_num'] ;
				  }
				  if(isset($billinginfo['x_card_code'])){
				  	 $x_card_code = $billinginfo['x_card_code'] ;
				  }else{
				  	$x_card_code = "";
				  }
				   if(isset($billinginfo['x_exp_date'])){
				  	 $rowProfile->cb_expdate = $billinginfo['x_exp_date'] ;
				  }
				  $size = count($cardtypearr);
				if($size==1){
				   echo $cardtypearr[0];
				   
				    ?>
                    <input type="radio" style="display:none"  name="cardtype" value="<?php echo  $cardtypearr[0];?>"  <?php  echo "checked"; ?> />
                  <?php
				   
				}
				 
				   if($size>1)
				for($i=0;$i<count($cardtypearr);$i++)

				{?>

		        <input type="radio" name="cardtype" value="<?php echo  $cardtypearr[$i];?>"  <?php if($cardtypearr[$i]==$cardType) echo "checked"; ?> /><?php echo  $cardtypearr[$i];?><br />

				<?php } ?>

		       </td>

		        </tr>

		        <tr>
                 
		          <td width="31%" ><?php echo JText::_( 'CARD_NUMBER' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		         <td width="69%" align="left" ><input type="text" name="x_card_num" onKeyUp="chknumber(this)" class="inputbox" value="<?php echo $rowProfile->cb_creditcardnumber?>" />

		              <br />

		            <?php echo JText::_( 'CARD_NUMBER_EXPLANATION' );?></td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CARD_EXPIRY_DATE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		          <td width="69%" align="left" ><input type="text" name="x_exp_date" value="<?php echo $rowProfile->cb_expdate?>" class="inputbox" />

		            &nbsp;&nbsp;(mm/yy)</td>

		        </tr>

		        <tr>

		          <td width="31%" ><?php echo JText::_( 'CVV_CODE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td>

		         <td width="69%" align="left" ><input type="text" name="x_card_code" size="10" onKeyUp="chknumber(this)" class="inputbox" value="<?php echo $x_card_code ;?>" />

		            <?php echo JText::_( 'CVV_CODE_EXPLANATION' );?></td>

		        </tr>

		        <tr>

		          <td>

                  <input type="button" onclick='window.location="<?php echo JRoute::_("index.php?option=com_dtregister&task=paymentchanges&Itemid=".$Itemid,$xhtml_url)  ?>"' class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

                  <input type="button" name="send" value="<?php echo JText::_('DT_NEXT_BUTTON'); ?>" class="button" onclick="sendPayment();" /></td>

		          <td align="left" >&nbsp;<input type="hidden" name="authPayment" value="1" /><input type="hidden" name="option" value="com_dtregister" /><input type="hidden" name="task" value="paymentchanges" /><input type="hidden" name="type" value="processchgAuthorizenet" /></td>

		        </tr>

		        </table>

	      </form>
		 <script language="javascript" type="text/javascript">
		  //<![CDATA[
		  function chknumber(txtname){

			var num = txtname.value
           
			   if(isNaN(num)){

							alert("<?php echo JText::_( 'DT_NUMBERS_ONLY' ); ?>");

							txtname.value = "";

					    	txtname.focus();

						}

			}
			function sendPayment(){
              var form=document.frmcart;
			  
			  <?php

						if(1){ // $dt_user->userType=="I"

						?>

						if(form.billing_firstname.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_FIRSTNAME_ERROR' ); ?>");

							form.billing_firstname.focus();

							return ;

						}

						if(form.billing_address.value==""){

							alert ("<?php echo JText::_( 'DT_ADDRESS_ERROR' ); ?>");

							form.billing_address.focus();

							return ;

						}

						if(form.billing_city.value==""){

							alert ("<?php echo JText::_( 'DT_CITY_ERROR' ); ?>");

							form.billing_city.focus();

							return ;

						}

						if(form.billing_state.value==""){

							alert ("<?php echo JText::_( 'DT_STATE_ERROR' ); ?>");

							form.billing_state.focus();

							return ;

						}

						if(form.billing_zipcode.value==""){

							alert ("<?php echo JText::_( 'DT_ZIP_ERROR' ); ?>");

							form.billing_zipcode.focus();

							return ;

						}

						if(form.billing_email.value==""){

							alert ("<?php echo JText::_( 'DT_EMAIL_ERROR' ); ?>");

							form.billing_email.focus();

							return ;

						}

						<?php

						}

						?>

			  var checked=false;
			     if(typeof form.cardtype.length =='undefined'){
						   checked =true ;
						    cardType = form.cardtype.value;
						}
			  
						for(var i=0;i<form.cardtype.length;i++){

							if(form.cardtype[i].checked==true){

								cardType = form.cardtype[i].value;

								checked=true;

								break;

							}

						}

						if(!checked){

							alert ("<?php echo JText::_( 'DT_CC_CARD_TYPE' ); ?>");

							return;

						}
						if(form.x_card_num.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_NUMBER' ); ?>");

							form.x_card_num.focus();

							return ;

						}

						if(form.x_exp_date.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_EXPIRE_DATE' ); ?>");

							form.x_exp_date.focus();

							return ;

						}

						if(form.x_card_code.value==""){

							alert ("<?php echo JText::_( 'DT_CARD_CODE' ); ?>");

							form.x_card_code.focus();

							return ;

						}
						
					   confirmText = "<?php echo JText::_( 'DT_CONFIRM_CC_INFO' ); ?>\n\n";
					   confirmText = confirmText+"\n<?php echo JText::_( 'CARD_TYPE' ); ?> \t: "+cardType+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CARD_NUMBER' ); ?> : "+form.x_card_num.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CARD_EXPIRY_DATE' ); ?> : "+form.x_exp_date.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'CVV_CODE' ); ?>:\t "+form.x_card_code.value+"\n";
						
						 confirmText = confirmText+"<?php echo JText::_( 'DT_AMOUNT' ); ?>:\t <?php echo $amount; ?>";

						var answer = confirm(confirmText);

						if (answer){
                            document.frmcart.send.disabled = true ;
							form.submit();

						}
              
			}
		 //]]>
		 </script>
            <?php
				
	 break ;
	 case "echeck":
	    $_SESSION['register']['payment_type'] = "echeck" ;
	    if($cb_integrated == 1){
         $userId=$user->id;
         if ($userId){
		   //Get the information from cb
           $sql="Select * From #__comprofiler where user_id=$userId";
           $database->setQuery($sql);
		   $rowProfile =  false ;
           if($cb_integrated==1)
           $rowProfile = $database->loadObject();
           if($rowProfile){
             //Decode some string
             global $ptc;
             $ptc->ToDecode=$rowProfile->cb_creditcardnumber;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
                $rowProfile->cb_creditcardnumber=$ptc->Decoded;
             $ptc->ToDecode=$rowProfile->cb_expdate;
             $ptc->Decode();
             if($ptc->Decoded!=-1)
               $rowProfile->cb_expdate=$ptc->Decoded;
           }
          }
         }
	   ?>
       <form name="frmcart" method="post" action="index.php">
       <table>
          <?php  billingform($dt_user); ?>
         <tr><td colspan="2" ><strong><?php echo JText::_( 'DT_BANK_INFORMATION' ) ?></strong><br /></td></tr>
          <tr><td><?php echo JText::_( 'DT_BANK_ROUTING_NUMBER' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

					<td><input type="text" name="x_bank_aba_code" onKeyUp="chknumber(this)" class="inputbox"  size="20" maxlength="16" value="<?php echo $rowProfile->cb_routingnumber?>"/></td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_NUMBER' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><input type="text" name="x_bank_acct_num" onKeyUp="chknumber(this)" class="inputbox"  size="20" maxlength="16" value="<?php echo $rowProfile->cb_acctnumber?>"/></td></tr>

			    <tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_TYPE' ) ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><select name="x_bank_acct_type">

			        	<option value="CHECKING" <?php echo($x_bank_acct_type=='CHECKING')?'selected':''?>><?php echo JText::_( 'DT_BANK_CHECKING' ); ?></option>

						<option value="SAVINGS" <?php echo($x_bank_acct_type=='SAVINGS')?'selected':''?>><?php echo JText::_( 'DT_BANK_SAVINGS' ); ?></option>

						</select>

			        </td></tr>
         <tr><td><?php echo JText::_( 'DT_BANK_NAME' ); ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td>

			        <td><input type="text" name="x_bank_name" class="inputbox" size="30" value="<?php echo $rowProfile->cb_bankname?>"/></td></tr>

			  	<tr><td><?php echo JText::_( 'DT_BANK_ACCOUNT_HOLDER' ); ?>:<span class='required'>&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;</span></td><td><input type="text" name="x_bank_acct_name" class="inputbox" size="30" value="<?php echo $rowProfile->cb_accountholder?>"/></td></tr>
	<tr><td colspan="2" align="center">&nbsp;</td></tr>

					<tr><td colspan="2" align="center">

						<input type="hidden" name="task" value="paymentchanges" />

						<input type="hidden" name="type" value="processchgEcheck" />
                        
                        <input type="hidden" name="option" value="com_dtregister" />

						  <input type="button" onclick='window.location="<?php echo JRoute::_("index.php?option=com_dtregister&task=paymentchanges&Itemid=".$Itemid,$xhtml_url)  ?>"' class="button" value="<?php echo JText::_('DT_BACK'); ?>" id="next" name="billingInfo"/>

						<input type="button" name="send" value="<?php echo JText::_( 'DT_SEND_BUTTON' ); ?>" class="button" onclick="sendPayment();" />

					</td></tr>
                
       </table>
       </form>
       <script language="javascript" type="text/javascript">
	     //<![CDATA[
					function chknumber(txtname){

						var num = txtname.value

					    if(isNaN(num)){

							alert("<?php echo JText::_( 'DT_NUMBERS_ONLY' ); ?>");

							txtname.value = "";

					    	txtname.focus();

						}

					}
		function sendPayment(){
		    var frm=document.frmcart;
			var form=document.frmcart;
			<?php
                         // $dt_user->userType=="I"
						if(1){

						?>

						if(form.billing_address.value==""){

							alert ("<?php echo JText::_( 'DT_ADDRESS_ERROR' ); ?>");

							form.billing_address.focus();

							return ;

						}

						if(form.billing_city.value==""){

							alert ("<?php echo JText::_( 'DT_CITY_ERROR' ); ?>");

							form.billing_city.focus();

							return ;

						}

						if(form.billing_state.value==""){

							alert ("<?php echo JText::_( 'DT_STATE_ERROR' ); ?>");

							form.billing_state.focus();

							return ;

						}

						if(form.billing_zipcode.value==""){

							alert ("<?php echo JText::_( 'DT_ZIP_ERROR' ); ?>");

							form.billing_zipcode.focus();

							return ;

						}

						if(form.billing_email.value==""){

							alert ("<?php echo JText::_( 'DT_EMAIL_ERROR' ); ?>");

							form.billing_email.focus();

							return ;

						}

						<?php

						}

						?>
if(frm.x_bank_aba_code.value==""){

								alert ("<?php echo JText::_( 'DT_BANK_ROUTING' ); ?>")

								frm.x_bank_aba_code.focus();

								return;

						}

						if(frm.x_bank_acct_num.value==""){

							alert ("<?php echo JText::_( 'DT_BANK_ACCOUNT' ); ?>")

							frm.x_bank_acct_num.focus();

							return;

						}

						if(frm.x_bank_name.value=='' || frm.x_bank_acct_name.value.charAt(0)==' '){

							  alert("<?php echo JText::_( 'DT_BANK_NAME' ); ?>");

							  frm.x_bank_name.focus();

							  return;

					  	}

						if(frm.x_bank_acct_name.value=='' || frm.x_bank_acct_name.value.charAt(0)==' '){

						  	alert("<?php echo JText::_( 'DT_BANK_USER' ); ?>");

						  	frm.x_bank_acct_name.focus();

							return;

						}

						confirmText = "<?php echo JText::_( 'DT_CONFIRM_BANK_ACCOUNT_INFO' ); ?>\n";
confirmText = confirmText+"\n<?php echo JText::_( 'DT_BANK_ROUTING_NUMBER' ); ?>:\t"+frm.x_bank_aba_code.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_NUMBER' ); ?>:\t"+frm.x_bank_acct_num.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_TYPE' ); ?>:\t\t"+frm.x_bank_acct_type.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_NAME' ); ?>:\t\t"+frm.x_bank_name.value+"\n";

						confirmText = confirmText+"<?php echo JText::_( 'DT_BANK_ACCOUNT_HOLDER' ); ?>:\t"+frm.x_bank_acct_name.value;

						var answer = confirm(confirmText);

						if (answer){

							frm.submit();

						}
		}
	    //]]>
	   </script>
       <?php
	 break; 
	 
	  default :{
	           
				$_SESSION['register']['payment_type'] = $paymethod ;
			    require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$paymethod .'.php');
			     $payment =  new $paymethod ();
				 //$payment->setBillinginfo($_SESSION['register']['billingInfo']);
				 if(isset($_SESSION['register']['cancel_paying_amount'])){
				    
					$type  = "cancel";
					
				 }else{
				    
					$type  = "change";
					
				 }
				 $payment->setPaymentType($type );
				 $payment->beforepayment();
				  $data =  array(
				        'eventName'=>  $dt_user->event->summary ,
						'amount'=>$amount 
				 );
				  if($_SESSION['register']['paymentMethod']=='GoogleCheckout')
				 echo "</form>";
				  echo '<form name="frmcart" method="post" action="index.php">' ;
				 $payment->setData($data);
				 $options = array('message'=>JText::_( 'DT_GOOGLECHECKOUT_REDIRECT_MSG' ));
				 echo $payment->showform( $options) ;
				
			}
	 
  }
  
}

function cancelthk($option){
   global $Itemid ,$mainframe ;
     if(isset($_REQUEST['dtevent'])){
			  
			  $sql  = "select * from #__dtregister_session where id=".$_REQUEST['dtevent'];

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();
    
			 $data = unserialize($row[0]->data);
             $userId = $row[0]->user_id ;
			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;
			 if($userId ==  0 || $userId==""){
			       
					require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['payment_type'].'.php');

                     $payment =  new $_SESSION['register']['payment_type']();

                     $payment->afterpayment();
					 $_SESSION['register']['transaction_id'] = $payment->TransactionID ;
					    $_SESSION['register']['transaction_id'] = $_REQUEST['txn_id'] ;
			            $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
						if($row[0]->user_id == 0){
			
						  $sql = "update #__dtregister_session set user_id='".$dt_user->id."' where id=".$_REQUEST['dtevent'] ;
			
						 $database->setQuery($sql);
			
						  $database->query();
			
					  }
					  if($_SESSION['register']['paymentMethod'] !="GoogleCheckout"){
					     $userId =  saveuser('com_dtregsiter',1);
					  }
						 
				}
		 }
   $mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,  JText::_( 'DT_CANCEL_SUCCESSFUL' ));
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $eventid=JRequest::getVar('eventId');
   $dt_evt = new Event($eventid);
   $upcancelmsg =  str_replace( "[EVENT_NAME]",$dt_evt->summary,$upcancelmsg) ;
   echo $upcancelmsg =  str_replace( "[EVENT_DATE]",get_date($dt_evt->dtstart,$dt_evt->dtend),$upcancelmsg) ;
     
    ?><p><a href="<?php echo JRoute::_('index.php?option=com_dtregister&Itemid='.$Itemid.'&task=history',$xhtml_url ); ?>" ><?php  echo JText::_( 'DT_RETURN_TO_PANEL' ); ?></a></p>
    <br /> 
   <?php
   

}

function paychgthk($option){
   global $Itemid ,$mainframe ;
    if(isset($_REQUEST['dtevent'])){
			  
			  $sql  = "select * from #__dtregister_session where id=".$_REQUEST['dtevent'];

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();
    
			 $data = unserialize($row[0]->data);
             $userId = $row[0]->user_id ;
			 $data = unserialize($row[0]->data);
            
			 $_SESSION = $data;
			 if($userId ==  0 || $userId==""){
			       
					require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/class.'.$_SESSION['register']['payment_type'].'.php');

                     $payment =  new $_SESSION['register']['payment_type']();

                     $payment->afterpayment();
					 $_SESSION['register']['transaction_id'] = $payment->TransactionID ;
					    $_SESSION['register']['transaction_id'] = $_REQUEST['txn_id'] ;
			            $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
						if($row[0]->user_id == 0){
			
						  $sql = "update #__dtregister_session set user_id='".$dt_user->id."' where id=".$_REQUEST['dtevent'] ;
			
						 $database->setQuery($sql);
			
						  $database->query();
			
					  }
					  if($_SESSION['register']['paymentMethod'] !="GoogleCheckout"){
					    $userId =  saveuser('com_dtregsiter',1);
					  }
						 
				}
		 }
   $mainframe->redirect( "index.php?option=com_dtregister&task=history&Itemid=".$Itemid ,  JText::_( 'DT_RECORD_CHANGE_SUCCESSFUL' ));
   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
   $eventid=JRequest::getVar('eventId');
   $dt_evt = new Event($eventid);
   $upthanksmsg =  str_replace( "[EVENT_NAME]",$dt_user->event->summary,$upthanksmsg) ;
   echo $upthanksmsg =  str_replace( "[EVENT_DATE]",get_date($dt_user->event->dtstart,$dt_user->event->dtend),$upthanksmsg) ;
   ?><p><a href="index.php?option=com_dtregister&task=history&Itemid=<?php echo $Itemid; ?>" ><?php  echo JText::_( 'DT_RETURN_TO_PANEL' ); ?></a></p>
    <br /> 
   <?php
   
}

function processchgEcheck($option, $Itemid){
  
  global $Itemid ,$mainframe ;
  $user = &JFactory::getUser();
  $database = &JFactory::getDBO();
  include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
  $amount = $_SESSION['billinginfo']['register']['pay_amount'];
  $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
  $dt_user->DT_User($dt_user->id,$dt_user->eventId);
  $amount  = $amount - $dt_user->paid_amount  ;
  $x_bank_acct_name = 	$database->getEscaped($_POST["x_bank_acct_name"]);

  $x_bank_name  = 		$database->getEscaped($_POST["x_bank_name"]);

  $x_bank_acct_type = 	$database->getEscaped($_POST["x_bank_acct_type"]);

  $x_bank_acct_num = 	$database->getEscaped($_POST["x_bank_acct_num"]);

  $x_bank_aba_code = 	$database->getEscaped($_POST["x_bank_aba_code"]);

  $userId=$user->id;
  if(!isset($ses_invoiceno)){

		$chars = "0123456789";

		srand((double)microtime()*1000000);

		for($i=0; $i<7; $i++){

   			$x_invoice_num1 .= $chars[rand()%strlen($chars)];

   		}

		$ses_invoiceno = "DC-".$x_invoice_num1;
		$dt_user  = new DT_User();
        $ses_invoiceno = $dt_user->generateconfirmNum();

   	}
 ?>
 <table border="0" cellpadding="3">

	<tr class="v">

		<td>
<?php
 $auth_net_login_id			= $merchid;

 $auth_net_tran_key			= $transkey;
 $authnet_values				= array

(

	"x_login"				=> $auth_net_login_id,

	"x_version"				=> "3.1",

	"x_delim_char"			=> "|",

	"x_delim_data"			=> "TRUE",

	"x_type"				=> "AUTH_CAPTURE",

	"x_method"				=> "ECHECK",

 	"x_tran_key"			=> $auth_net_tran_key,

 	"x_relay_response"		=> "FALSE",

	"x_amount"				=> $amount,

//  ###########3  CUSTOMER DETAILS  ################3

	"x_first_name"			=> stripslashes(stripslashes($x_bank_acct_name)),

	"x_last_name"			=> "",

  	"x_company"    		 	=> stripslashes(stripslashes($dt_user->userFirstName)),

	"x_address"				=> stripslashes(stripslashes(JRequest::getVar('billing_address','','post'))),

	"x_city"				=> JRequest::getVar('billing_city','','post'),

	"x_state"				=> JRequest::getVar('billing_state','','post'),

	"x_country"				=> $dt_user->userCountry,

	"x_phone"				=> $dt_user->userPhone,

	"x_zip"					=> JRequest::getVar('billing_zipcode','','post'),

	"x_email"				=> JRequest::getVar('billing_email','','post'),

	"x_cust_id"				=>$x_invoice_num1,

//  ###########3  SHIPPING DETAILS  ################3

	"x_ship_to_first_name" 	=>stripslashes(stripslashes($dt_user->userFirstName)),

	"x_ship_to_last_name" 	=>stripslashes(stripslashes($dt_user->userLastName)),

	"x_ship_to_address"  	=> stripslashes(stripslashes($dt_user->userAddress)),

	"x_ship_to_city" 		=>$dt_user->userCity,

	"x_ship_to_state" 		=> $dt_user->userState,

	"x_ship_to_country" 	=> $dt_user->userCountry,

	"x_ship_to_zip" 		=> $dt_user->userZip,

	"x_ship_to_phone" 		=> $dt_user->userPhone,

	"x_ship_to_email" 		=> $dt_user->userEmail,

	"x_ship_to_company" 	=> stripslashes(stripslashes($dt_user->userOrganization)),

	"x_invoice_num" 		=> $ses_invoiceno,

	"x_bank_aba_code"		=> $x_bank_aba_code,

	"x_bank_acct_num"		=> $x_bank_acct_num,

	"x_bank_acct_type"		=> $x_bank_acct_type,

	"x_bank_name"			=> $x_bank_name,

	"x_bank_acct_name"		=> stripslashes(stripslashes($x_bank_acct_name)),

	"x_echeck_type"			=> "WEB",

	"x_recurring_billing"	=> "NO",

	"x_description"	=> $dt_user->event->summary

);

$fields = "";
//echo "<pre>";

//print_R($authnet_values);
foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";

if($echecknetmode == "test"){

	$ch = curl_init("https://test.authorize.net/gateway/transact.dll");

	} else {

	$ch = curl_init("https://secure.authorize.net/gateway/transact.dll");

	}

if($godaddy_hosting){

	curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

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

}

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_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###

$resp = curl_exec($ch); //execute post and get results

curl_close ($ch);
echo "<hr />";

$text = $resp;

$res = explode('|',$resp);

switch($res[0]){

case 1:

			echo "<b>".JText::_( 'DT_PAYMENT_SUCCESSFUL' )."</b><br />";

			echo 'Amount: ',$res[9],'<br />';

break;

case 2:

if($res[2]==2 || $res[2]==4){

echo "<b>".JText::_( 'DT_PAYMENT_DECLINED' )."</b>";

echo DT_REASON .": ",$res[3];

}

break;

case 3:

echo "<b>". JText::_( 'DT_ECHECK_PAYMENT_FAILED' ) ."</b><br />";

echo JText::_('DT_REASON') .": ",$res[3],'<br />';

break;

default:

echo "<b>".JText::_( 'DT_ERROR' )."</b><br />";

echo $res[3] . '<br />';

break;

echo "<hr />";

///////////////////////////////////////////////

}

?>

		</td>

	</tr>

</table>

<?php

echo "<hr />";

if($res[0]==1){
$_SESSION['register']['transaction_id'] = $res[6] ; 
  saveuser('com_dtregsiter',1);

	$transactionid = $res[6];
	$transactionid = $ses_invoiceno ;
	// save the individual or group info
    // save  user
	//$user_id = saveInfo('E-Check (Authorize.net)', 1, $transactionid);

} else {
     
	  $billing_address=JRequest::getVar('billing_address','','post');

		$billing_city=JRequest::getVar('billing_city','','post');

		$billing_state=JRequest::getVar('billing_state','','post');

		$billing_zipcode=JRequest::getVar('billing_zipcode','','post');

		$billing_email=JRequest::getVar('billing_email','','post');

		$dt->user->billing_address=$billing_address;

		$dt->user->billing_state=$billing_state;

		$dt->user->billing_city= $billing_city;

		$dt->user->billing_city=$billing_city;

		$dt->user->billing_email=$billing_email ;
		
		 $_SESSION['billinginfo']['register']['user'] = serialize($dt_user) ;

    ?>
   <form id="frmBack" name="frmBack" method="POST" action="index.php">

	<input type="hidden" name="try_again" value="1" />

	<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />

	<input type="hidden" name="option" value="com_dtregister" />

	<input type="hidden" name="task" value="paymentchanges" />

	<input type="hidden" name="type" value="echeck" />

		<input type="hidden" name="x_bank_acct_name" value="<?php echo $x_bank_acct_name?>" />

		<input type="hidden" name="x_bank_name" value="<?php echo $x_bank_name?>" />

		<input type="hidden" name="x_bank_acct_type" value="<?php echo $x_bank_acct_type?>" />

		<input type="hidden" name="x_bank_acct_num" value="<?php echo $x_bank_acct_num?>" />

		<input type="hidden" name="x_bank_aba_code" value="<?php echo $x_bank_aba_code?>" />

		<!-- Other field in bank account info-->

		<input type="submit" class="button" value="<?php echo JText::_( 'DT_TRY_AGAIN' ); ?>" />

	</form>
 
    <?php
}

?>
 <?php
  
}
function paypal_paychgreturn(){
   global $Itemid , $mainframe; 
  /* $database = &JFactory::getDBO();

	$data = explode('|',$_REQUEST['custom']);
    foreach($data as $key=>$value){
      if(substr($value,0,7)=='session'){
        $arr = explode("=",$value);
        $paypal_session_id = $arr[1];
        break;
      }
    }
    $sql  = "select * from #__dtregister_session where id=$paypal_session_id";
    $database->setQuery($sql);
    $database->query();
    $row = $database->loadObjectList();
    $data = unserialize($row[0]->data);
	unset($_SESSION['billing']);
	unset($_SESSION['register']);*/
	paychgthk("com_dtregister");
    // save user ;;
	
}

function paypal_paychgfailure($option){
  // echo $message;
}
function fileupload(){
   $type = trim( JRequest::getVar('type', '') );
   $vars =  explode('|',$type);
   $name = $vars[0];
   $size = $vars[1];
   $types = explode(",",$vars[2]);
   $file = $_FILES["file_".$name];
 
   $newtype = array();
   foreach($types as $type){
      $newtype[] = ".".$type;
   }
   foreach($newtype as $val){
      $types[] = $val;
   }
   // echo "<pre>";
	//print_r($_POST);
	//print_r($_FILES);
  // print_r($file);
   //print_r($types);
  //echo "</pre>";
   $dt_file = new DT_file();
   jimport('joomla.filesystem.file');
   $ext = JFile::getExt($file['name']);
   
   if(in_array($ext,$types) || count($types) <1){
	   if(($file['size']/1000) <= $size){
	      $dt_file->upload($file,'uploads');
		  $value=$dt_file->path;
		  ?>
          <script type="text/javascript">
		     //<![CDATA[
		     parent.DTjQuery('#<?php echo $name;?>').val('<?php echo JFile::getName($dt_file->path) ?>');
			 parent.DTjQuery('#<?php echo $name;?>').parent().append("<br /><?php echo JText::_( 'DT_FILE_UPLOADED' ) ?>");
			 //jQuery("#My_Pic").before(document.createTextNode("Hello"));
			 //parent.jQuery('#<?php echo $name;?>');
			 
			 //]]>
		  </script>
          <?php
	    }else{// file error
		   ?>
            <script type="text/javascript">
			   //<![CDATA[
		      alert('<?php echo JText::_( 'DT_ERROR_FILE_SIZE' ); ?>');
			  //]]>
		  </script>
           <?php
		}
	}else{// file type not valid
	     ?>
            <script type="text/javascript">
			   //<![CDATA[
		      alert('<?php echo JText::_( 'DT_ERROR_FILE_TYPE' ); ?>');
			  //]]>
		   </script>
           <?php    
	}		  		   
   
   die;
   
}

function getconditonField(){
  global $mainframe ; 
   
  $field = new Custom_field(JRequest::getVar('field_id',0));
  $field->read();
  
  $childs = $field->getchild();
  $selectionindex = JRequest::getVar('selection','');
  
  $not_remove =  JRequest::getVar('not_remove',array());
  if($field->type == 1){
     $selectionindex-- ;
  }
   
   $elements = array();
   $event = new Event(JRequest::getVar('eventId',0));
   $childjs = "" ;
   $user = unserialize(base64_decode(JRequest::getVar('obj','')));
   $evt_fields = $event->getAllFields();
   $remove_elements = array();
   $ordering =  array();
  foreach($childs as $key=>$child){
  
     $selection =  explode(',',$child->selection_values);
	$ordering[$child->id] = $child->ordering ;
	$selectionindex ;
	 if(in_array($selectionindex,$selection)){
	    $child = new Custom_field($child->id);
		$child->read();
		if(isset($evt_fields[$child->id])){
		  // $child->required = $evt_fields[$child->id]->required ;
		}
		$file = JPATH_SITE."/components/com_dtregister/view/field/field".$field->type.".php";
		  
		  if (!file_exists($file)) {
		     $file = JPATH_SITE."/components/com_dtregister/view/field/field.php";
		  }
		  $child->label = stripslashes($child->label).":";
		  if($child->required){
		    $child->label = $child->label." <span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span> ";
		  }
		  
		  $tpl = file_get_contents($file);
		  $constants = array('[label]','[value]','[description]');
		  $description =  (trim($child->description)!="")?JHTML::tooltip($child->description, '', 'tooltip.png', '', ''):'';
		  $replace  = array($child->label,$child->formhtml($user,$event,$form,$overlimitdisable),str_replace('hasTip','FieldTip'.$child->id,$description));
		  $childjs .= $child->childJs ;
		  $elements[$child->id] = str_replace($constants,$replace,$tpl);
		   
		 //  print_r($elements);
		
	 }else{
	    $remove = true ;
	    foreach($selection as $val){
		    if(in_array($val,$not_remove)){
			   $remove = false;
			   break ;
			} 
		}
		
		if($remove){
		  $remove_elements[$child->id] = $child->id ;
		}
	    
	 }
	 
    // print_r($child);
	 
  }
  $temp = $remove_elements ;
  
 foreach($remove_elements as $remove_element){
	  $rChilds = array();
	  
	  $field->findtree($remove_element,$rChilds);
	  
	  foreach($rChilds as $rchild){
		  if(!in_array($rchild->id,array_keys($elements)))
		  $temp[$rchild->id] = $rchild->id;
	  }
	
 }

 $remove_elements = $temp ;
  ob_start();
	 ?>
     var elements = <?php echo json_encode($elements); ?>;
	 var remove_elements = <?php echo json_encode(array_reverse($remove_elements,TRUE )); ?>;
     
     var ordering = <?php echo json_encode($ordering); ?>;
     
     <?php
	 echo $childjs ;
	 $data =  ob_get_clean();
	 
	 echo str_replace("\n",' ',$data)."/*DTendScript*/";
	 die ;
  
}

/********************************

 * Here is the logic that calls

 * the functions above

 *******************************/

$database = &JFactory::getDBO();

// GET parameters

 $task = trim( JRequest::getVar('task', '','request' ) );

 $type = trim( JRequest::getVar('type', '','request' ) ); 

$eventId = trim( JRequest::getVar('eventId', '' ) );

if(!isset($_SESSION['register']['Itemid']) || $_SESSION['register']['Itemid']==''){

	$_SESSION['register']['Itemid'] = trim($_REQUEST['Itemid']);

	$Itemid = $_SESSION['register']['Itemid'];

}else{

	$Itemid = $_SESSION['register']['Itemid'];

}

// Initial visit - nothing selected - display list of events

if (!$eventId && !$type && !$task){

	$_SESSION['register'] = NULL;

	$_SESSION['register']['Itemid'] = $Itemid;
    if(isset($_REQUEST['payer_email'])){
	///if(0){
	   	
	 }else{
	   listEvents($option);
	 }

// event selected

} else {

	$_SESSION['register']['eventId'] = $eventId;

	$_SESSION['register']['task'] = $task;

	// These are all of the options from the event list page

	if ($task == "cut_off_date" || $task == "full_event_page" || $task == "reg_event" || $task == "full_event_page_msg" || $task=="sign_up" || $task =="prerequisite" || $task =='overlap'){

		// table_header($task, $type);

		switch ($task){

			case "cut_off_date":

				table_header($task, $type);

				cutOffDate($option);

			break;

			case "full_event_page":

				table_header($task, $type);

				fullEventPage($option);

			break;

			case "full_event_page_msg":

				table_header($task, $type);

				fullEventPageMsg($option);

			break;

			case "reg_event":

				table_header($task, $type);

				event_register($option, $eventId);

			break;

			case "sign_up" :

				include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");

				echo stripslashes($private_event_msg) . '<br /><br />';

			break;
			
			case 'prerequisite':
			   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
			   $evet = new Event($eventId);
               $prerequisite =  $evet->get_prerequisite();
	           $selection = array();
			   
	           foreach($prerequisite as $select){
			     
					$pre_evt = new Event($select->prerequisite_id);
				   $selection[] = $pre_evt->summary ;
				    
		       }
			   $prerequisite = "<ul><li>".implode("</li><li>",$selection)."</li></ul>";
			   
			    echo str_replace("[PREREQ_EVENTS]",$prerequisite,$prerequisite_event_msg);
				
			break;
			case 'overlap':
			   include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
			   echo $overlap_event_msg ;
			   
			break;

		}

	// task=event_register&type=duplication_check

	// get the individual and group registration(billing) info

	// get number in group and group users

	} else if ($task == "event_register"){
      
		$my = &JFactory::getUser();
        
		if( $my->id){

			$viewPublicPrivate = "AND (b.public=1 OR b.public=0) ";

		} else {

			$viewPublicPrivate = "AND b.public=1 ";

		}

			$sql = "SELECT DISTINCT(a.evdet_id)

			FROM #__jevents_vevdetail a, #__dtregister_group_event b

			WHERE a.evdet_id = b.eventId AND b.eventId=".$_SESSION['register']['eventId']."  AND a.dtend >= '". $now->toUnix(true) ."' AND a.state=1 ".

			$viewPublicPrivate;

			$database->setQuery($sql);
			
			$rows = $database->loadObjectList();

			if(!(count($rows) > 0) && $type!="security_check"){

				$url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);

			}
           $dt_evt = new Event($_SESSION['register']['eventId']) ;
		   global $usetimecheck  ;
		   
		  $dt_evt->over_ride_global(true);
		  
		if(!$dt_evt->is_registerable() && ($type!="save_waiting" && $type!="security_check" )){
		    $mainframe->redirect($dt_evt->redirection );
		}
		 if($my->id && $timecheck && $usetimecheck==0){
		      $dt_user = new DT_User();
		      $registerations = $dt_user->find('u.user_id ='.$my->id.' and u.cancel in(0,2)',"u.userId");
			  //$registerations = $dt_user->find('u.user_id =62',"u.userId");
			  //echo "<pre>";
			  //print_r($registerations);
			  //echo "</pre>"; die ;
			  if($dt_user->check_overlap($dt_evt,$registerations)){
			    
			     $url="index.php?option=$option&Itemid=$Itemid&task=overlap";

					$mainframe->redirect($url);
			  }
		  }
		 
		   $prerequisite = $dt_evt->get_prerequisite();
		   
		  if(is_array($prerequisite) and count($prerequisite)>0){
		     if(!$my->id){
			     // show messge to login ;
				 $url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);
			 }else{
			    //
				
				$dt_user = new DT_User();
		
				$attent_sql = "";
				$paid_sql = "";
				if($prerequisite_paid==1){
				   $paid_sql = " and u.pay_later_paid=1 ";
				}
				if($prerequisite_attend==1){
				   $attent_sql = " and u.attend=1 ";
				}
				$registerations = $dt_user->find('u.user_id ='.$my->id.$attent_sql.$paid_sql,"u.userId");
				
				//$registerations = $dt_user->find('u.user_id =62'.$attent_sql.$paid_sql,"u.userId");
				
				if(!$dt_user->check_prerequisite($prerequisite,$registerations)){
				   // show message ;
				   $url="index.php?option=$option&Itemid=$Itemid&task=prerequisite&Itemid=".$Itemid."&eventId=".$eventId;
                    
					//die("Prequisite check.");
					$mainframe->redirect($url);
				   
				}
				
			 }
		  }
		  
		  $prerequisite_cat = $dt_evt->get_prerequisite_category();
		  
		  if(is_array($prerequisite_cat) and count($prerequisite_cat)>0){
			 if(!$my->id){
			     // show messge to login ;
				 $url="index.php?option=$option&Itemid=$Itemid&task=sign_up";

					$mainframe->redirect($sign_up_redirect);
			 }else{
			    $dt_user = new DT_User();
		
				$attent_sql = "";
				$paid_sql = "";
				if($prerequisite_paid==1){
				   $paid_sql = " and u.pay_later_paid=1 ";
				}
				if($prerequisite_attend==1){
				   $attent_sql = " and u.attend=1 ";
				}
				$registerations = $dt_user->find('u.user_id ='.$my->id.$attent_sql.$paid_sql,"u.userId");
			
				if(!$dt_user->check_prerequisite_cat($prerequisite_cat,$registerations)){
				   // show message ;
				   $url="index.php?option=$option&Itemid=$Itemid&task=prerequisite&Itemid=".$Itemid."&eventId=".$eventId;
                    
					$mainframe->redirect($url);
				   
				}
				
			 }
			 
		  }
		 
		//table_header($task, $type);
        $dt_evt->resume_global();
         $dt_evt->over_ride_global();
		switch($type){

			case "reg_options":

				table_header($task, $type);

				$_SESSION['register']['reg_type'] = $type;

				if (!checkRegCutoff($eventId)){

					reg_options($option,$eventId);

				} else {

					cutOffDate($option);

				}

				break;

			case "reg_individual":

				table_header($task, $type);
                
				$_SESSION['register']['memtot'] = 1;
				
				$_SESSION['register']['reg_type'] = $type;

				if (!checkRegCutoff($eventId)){ billingInfo($option,$eventId,1);

				} else { cutOffDate($option); }

				break;

			case "reg_group_billing":

				table_header($task, $type);

				billingInfo($option,$eventId,$_SESSION['register']['memtot']);

				#echo $type;

				break;

			case "reg_group_num":

				// display the form to enter the number of group size(memtot)

				table_header($task, 'reg_group_users');

				$_SESSION['register']['reg_type'] = 'reg_group';

				if (!checkRegCutoff($eventId)) { getGroupNum($option, $eventId);

				} else { cutOffDate($option); }

				break;

			case "get_group_users":

				table_header($task, $type);

				// loop through for each group user

				   regGroupUsers($option, $eventId);

				break;

			case "addGroupUser":

				table_header($task, $type);

				// loop through for each group user

				saveGroupInfo($option, $eventId);

				break;

			case "reg_info_check":

				table_header($task, $type);
                if(!isset($_SESSION['register']['reg_type']) || $_SESSION['register']['reg_type'] == ""){
				   $_SESSION['register']['reg_type'] = $_GET['type'];
				}
				registration_info_check($option, $eventId);

				break;

			case "duplication_check":

				duplicationCheck($option);
                die;
				break;

			case "save_waiting":

				saveWaiting($option,$eventId);

				break;

			case "security_check":
                ob_clean();
				securityCheck($option);
                die ;
				break;

		}

	// get the payment type selected

	} else if ($task == "payment"){
        
        if(!isset($_SESSION['register']['billingInfo'])){
		   $mainframe->redirect("index.php?option=com_dtregister");
		}
        if(isset($_POST['partial_payment']) && amount_filter($_POST['partial_payment']) > 0){
		   
		   $_SESSION['register']['billingInfo']['due_payment'] = $_SESSION['register']['amountCharged']-amount_filter($_POST['partial_payment']);
		   
		   $_SESSION['register']['billingInfo']['partial_payment'] = amount_filter($_POST['partial_payment']) ; 
		   
		}
		
        if(!isset($_SESSION['register']['paymentMethod']) || $_SESSION['register']['paymentMethod']=='')
		$_SESSION['register']['paymentMethod'] = $type;
     
		//if ($_SESSION['register']['amountCharged']==0 && $_SESSION['register']['billingInfo']['customFee']==0){$type="free";}

        if($type== "ideal"|| $type == 'GoogleCheckout' || $type =='NetDeposit'||$type=='Eway'){
           
		    table_header($task, $type);

			displayPaymentForm($type);
			
		}else if ($type == "authorizenet" || $type == "echeck"){

			table_header($task, $type);

			displayPaymentForm($type);

		} else if ($type == "paypal" || $type=='idealRabo'){

			displayPaymentForm($type);

		} else if ($type == "free" || $type == "pay_later"){

			table_header($task, $type);

			if($type=="free"){

				$pay_status = 1;

			}else{

				$pay_status = 0;

			}
			saveInfo($type, $pay_status);

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

			table_header($task, $type);

			processAuthorizenet($option, $Itemid);

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

			table_header($task, $type);

			processEcheck($option, $Itemid);

        } else if ($type == "processNetDeposit" || $type=="processpayment"){

			table_header($task, $type);
            
			processpayment($option, $Itemid);

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

 		  // table_header($task, $type);

		   ob_clean();

		   processIdeal($option, $Itemid);

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

			table_header($task, $type);

			paypal_complete($option);

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

			session_restore();

			table_header($task, $type);

			paypal_payreturn($option);

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

			//session_restore();

			table_header($task, $type);

			paypal_payfailure($option);

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

			paypal_notify();

			die;

		} else if($type=='idealRaboSuccess'){
		   
			 idealRaboSuccess($option);
			
		 } else if($type=='idealRaboCancel'){
		    
			 idealRaboCancel($option);
			
		 } else if($type=='idealRaboError'){
		   
			 idealRaboError($option);
			
		 } else {

			table_header($task, $type);

			payoptions($option, $eventId);

		}

	}else if($task=="registrant_list"){

		table_header($task, $type);

		list_registrants($option);

	} else if($task == "idealdueReturn"){
	    idealdueReturn($option);
	}else if($task == "idealdueReport"){
	    idealdueReport($option);
	} else if($task == "idealchgReturn"){
	    idealchgReturn($option);
	}else if($task == "idealchgReport"){
	    idealchgReport($option);
	} else if($task=="idealReturn"){

	   table_header($task, $type);

	    ideal_return($task);

	}else if($task=="googleReturn" || $task =="paymentReturn"){
       $sql  = "select * from #__dtregister_session where id=".$_REQUEST['dtevent'];

			 $database->setQuery($sql);

			 $database->query();

			 $row = $database->loadObjectList();

			 $data = unserialize($row[0]->data);
             $dt_userId = $row[0]->user_id ;
			
			 $_SESSION = $data;
			
	   table_header($task, $type);

	    google_return($task);

	}else if($task=="idealReport"){

	  // table_header($task, $type);

	    ideal_report($task);

	}else if($task=="showlocation"){

	     showlocation($task);

	}else if($task=="thumb"){

		thumb($option);

	}else if($task == "history"){
	    
		history($option);
	}else if($task == "dtregedit"){
	    
		editUser($option);
		
	}else if($task =="saveuser"){
	    saveuser($option);
	}else if($task == "confirmchanges"){
	  
	    confirmchanges($option);
	}else if($task=="confirmpay"){
	       confirmpay($option);
	}else if($task=="listmembers"){
	 
	     listmembers($option);
	
	}else if($task =="editmember"){
	   
	    editmember($option);
	     
	}else if($task =="savemember"){
	   
	   savemember($option);
	}else if($task=="removemember"){
	   removemember($option);
	}else if($task == "addmember"){
	    addmember($option);
	}else if($task =="savenewmember"){ 
	   savenewmember($option);
	}else if($task == "cancel"){
	   cancelregisteration($option);
	}else if($task == "due_payment"){
	    
	   if($type=="pay_later"){
	      $arr = array(1=>'atdoor',2=>'mailin',3=>'callin');
		  
		  $type = JRequest::getVar('pay_later_option', '' );
		  $type = $arr[$type];
		  
		  saveduepayment($type,1);
		  
	   }
	   
	   if ($type == "authorizenet" || $type == "echeck" || $type=="idealRabo"){
            
			duepaymentForm($type);

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

			duepaymentForm($type);

		}else if ($type == "ideal" || $type=="GoogleCheckout" || $type=='NetDeposit'){
            
			duepaymentForm($type); 

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

			processdueAuthorizenet($option, $Itemid);
			
		}else if ($type == "processdueIdeal"){

			processdueIdeal($option, $Itemid);
			
		} else if ($type == "processdueEcheck"){

			processdueEcheck($option, $Itemid);

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

			table_header($task, $type);

			paypal_due_complete($option);

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

			session_restore();
            paypal_payduereturn($option);
			
		} else if ($type == "paypal_payduefailure"){

			session_restore();

			paypal_payduefailure($option);

		} else if ($type == "paypal_due_notify"){
            session_restore();
			paypal_due_notify();

			die;

		}else if($type=='idealRaboSuccess'){
		   
			 dueidealRaboSuccess($option);
			
		 } else if($type=='idealRaboCancel'){
		    
			 dueidealRaboCancel($option);
			
		 } else if($type=='idealRaboError'){
		   
			 dueidealRaboError($option);
			
		 } else if($type=='processNetDeposit'){
		    
			 processdueNetDeposit($option);
			
		 }else{
		 
		   paydueopts($option);
		}
	   
	}else if($task == "paymentchanges"){
	 
	   $dt_user = unserialize($_SESSION['billinginfo']['register']['user']);
       $dt_user->DT_User($dt_user->id,$dt_user->eventId);
	   
	   if(!isset($_SESSION['billinginfo']['register']['feechanges']) || $_SESSION['billinginfo']['register']['pay_amount'] <= 0){
	      
		  saveuser($option,1);
		  
		  return; 
	   }
	   if ($type == "authorizenet" || $type == "echeck"){
            
			paymentForm($type);

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

			paymentForm($type);

		} else if ($type == "ideal" || $type=="idealRabo" || $type=="GoogleCheckout" || $type=='NetDeposit'){

			paymentForm($type);

		}else if ($type == "free" || $type == "pay_later"){

			if($type=="free"){

				$pay_status = 1;

			}else{

				$pay_status = 0;

			}
			 saveuser($option,$pay_status);
			 return ;
			//$mainframe->redirect("index.php?option=com_dtregister&Itemid=".$Itemid."&task=saveuser");
            // saveuser;
		   
		} else if ($type == "processchgAuthorizenet"){

			processchgAuthorizenet($option, $Itemid);
	    }else if ($type == "processNetDeposit"){

			processchgNetDeposit($option, $Itemid);
	    
		}else if ($type == "processchgIdeal"){

			processchgIdeal($option, $Itemid);
	    
		} else if ($type == "processchgEcheck"){

			processchgEcheck($option, $Itemid);

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

			table_header($task, $type);

			paypal_complete($option);

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

			session_restore();
            paypal_paychgreturn($option);
			
		} else if ($type == "paypal_paychgfailure"){

			session_restore();

			paypal_paychgfailure($option);

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

			paypal_notify();

			die;

		}else if($type=='idealRaboSuccess'){
		   
			 chgidealRaboSuccess($option);
			
		 } else if($type=='idealRaboCancel'){

			 chgidealRaboCancel($option);
			
		 } else if($type=='idealRaboError'){
		   
			 chgidealRaboError($option);
			
		 }else{
		   paychangesopts($option);
		}
	   
	}else if($task=='fileupload'){
	
	   ob_clean();
	   fileupload();
	   die;
	}else if($task == 'category'){
	   	$_SESSION['register'] = NULL;

	    $_SESSION['register']['Itemid'] = $Itemid;

	   listEvents($option);
	}else if($task == "cancelthk"){
	   cancelthk($option);
	}else if($task == "paychgthk"){
	   paychgthk($option);
	}else if($task == "gchgReturn" || $task == "chgReturn"){
	   paychgthk($option);
	}else if($task == "gcancelReturn" || $task == "cancelReturn"){
	   cancelthk($option);
	}else if($task == "gdueReturn" || $task == "duepaymentReturn"){
	   payduethk($option);
	}else if($task == 'getconditonField'){
	  
	    getconditonField();
	   die('good');
	}

}

?>
<div style="display:none;">
<iframe name="fileupload">

</iframe>
</div>