<?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
*/

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

class DTmosGroups extends JTable {

  var $groupid=null;

  function __construct( &$db ) {

    parent::__construct( '#__dtregister_group', 'groupId', $db );

  }

}

class mosDtCategory extends JTable {

  var $categoryId=null;

  var $categoryName=null;

  var $ordering = null;
  
  var $parent_id = 0 ;

  function __construct( &$db ) {

    $this->db = $db ;

    parent::__construct( '#__dtregister_categories', 'categoryId', $db );

  }

  function hasChild(){
    
	$query = "Select count(*) from #__dtregister_categories where parent_id=".$this->categoryId;
	$this->db->setQuery($query);
	
	return ($this->db->loadResult()>0);
	
  }
  
}

class myGroupEvent extends JTable {

  var $slabId=null;

  var $eventId=null;

  var $memberTotal=null;

  var $regGroupRate=null;

  var $regGroupPerRate=null;

  var $registerAmountIndividual=null;

  var $latefee=null;

  var $latefeedate=null;

  var $email=null;

  var $maxregistrations=null;

  var $registration_type=null;

  var $topmsg=null;

  var $cut_off_date=null;

  var $discount_type=null;

  var $discount_amount=null;

  var $thksmag=null;

  var $event_describe=null;

  var $event_describe_set=null;

  var $terms_conditions_set=null;

  var $terms_conditions_msg=null;

  var $category=null;

  var $ordering=null;

  function __construct( &$db ) {

    parent::__construct( '#__dtregister_group_event', 'slabId', $db );

  }

}

class myGroupEventReorder extends JTable {

  var $slabId=null;

  var $eventId=null;

  var $memberTotal=null;

  var $regGroupRate=null;

  var $regGroupPerRate=null;

  var $registerAmountIndividual=null;

  var $latefee=null;

  var $latefeedate=null;

  var $email=null;

  var $maxregistrations=null;

  var $registration_type=null;

  var $topmsg=null;

  var $cut_off_date=null;

  var $discount_type=null;

  var $discount_amount=null;

  var $thksmag=null;

  var $event_describe=null;

  var $event_describe_set=null;

  var $terms_conditions_set=null;

  var $terms_conditions_msg=null;

  var $category=null;

  var $ordering=null;

  function __construct( &$db ) {

    parent::__construct( '#__dtregister_group_event', 'eventId', $db );

  }

}

//Here are the new class for custom fieds
if(!class_exists('mosField')){
class mosField extends JTable {

  var $id=null;

  var $name=null;

  var $label=null;

  var $field_size=null;

  var $description=null;

  var $ordering=99;

  var $published=1;

  var $required=0;

  var $type=0;

  var $values=null;

  var $selected=null;

  var $rows=null;

  var $cols=null;

  var $fee_field=null;

  var $fees=null;

  var $fee_type=1;

  var $new_line=0;

   var $textual='';

   var $usagelimit = ""; 

    var $filetypes = ""; 
   
   var $upload = ""; 

   var $filesize = ""; 
   
   var $hidden = "";
   
   var $allevent = "";
   
   var $group_behave = 0;
   
   var $showed = 0;
   
   var $maxlength = "" ;
   
   var $date_format = "" ;
   
   var $parent_id = "" ;
   var $selection_values = "" ;
   
   var $textareafee = ""; 
   
   var $showcharcnt = 0 ;

  function __construct( &$db ) {
    $this->db = $db ;
    parent::__construct( '#__dtregister_fields', 'id', $db );

  }
  
  function enableALLEvents(){
	  $query = "delete  from #__dtregister_field_event where showed = 0 and field_id = ".$this->id ;
	 $this->db->setQuery($query);	
	// pr ($this->db->getQuery());
	 $this->db->query(); 
	  $error =  $this->db->getErrorMsg();
		 
		 if($error){
			 echo $error ; die ;
		 }
     $query = " SELECT DISTINCT e.eventId
					FROM #__dtregister_group_event as e
					LEFT JOIN #__dtregister_field_event as d ON e.eventId = d.event_id
					AND d.field_id  = ".$this->id."
					WHERE 
					 e.publish =1 
					
					AND d.event_id IS NULL ";
	   
	   $this->db->setQuery($query);		
	   
	    $this->db->getQuery();
	   
	   $data = $this->db->loadRowList();
	  
	   foreach($data as $evtid){
	      
		  $value = $evtid[0];
	      $query = "insert #__dtregister_field_event set event_id =".$value.", field_id =".$this->id.", showed = -1 , required = ".$this->required." , group_behave= ".$this->group_behave." ";
		  $this->db->setQuery($query);		
		  $this->db->query();	
		  
		  $this->db->getErrorMsg();
	         
	   }

  }

}
}
class mosGroupsHTML{

    function buildEventSelect($catid, $args){

        global $gid, $option;

        $database = &JFactory::getDBO();

		$sql="SELECT distinct(eventid) FROM #__dtregister_group_event";

		$database->setQuery($sql);

		$rows=$database->loadObjectList();

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

		{

			$eventidArr[]=$rows[$i]->eventid;

		}

		if(count($eventidArr)>0){

		$eventIdValue = implode(",", $eventidArr);

		 $catsql = "SELECT evdet_id AS value, summary AS text,  dtstart FROM #__jevents_vevdetail a"

	        . "\n WHERE a.evdet_id not IN(".$eventIdValue.")"

	        . "\n ORDER BY title";

			}else{

		 $catsql = "SELECT evdet_id  AS value, summary AS text, dtstart FROM #__jevents_vevdetail"

	        . "\n ORDER BY summary";

			}

        // get list of categories

        $groups[] = JHTML::_('select.option','', _CAL_LANG_EVENT_CHOOSE_CATEG );

        $database->setQuery($catsql);

        $rowEvents=$database->loadObjectList();

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

        {

        	$rowEvent=$rowEvents[$i];

        	$value=$rowEvent->value;

        	$text=$rowEvent->text.' ' .JFactory::getDate($rowEvent->dtstart)->toFormat('%m/%d/%y');//" ( ".JDate::_('toFormat',$rowEvent->dtstart,'%m/%d/%y')." )";

        	$groups[]=JHTML::_('select.option',$value,$text);

        }

        $clist = JHTML::_('select.genericlist', $groups, 'slabId', $args, 'value', 'text', $catid );

        echo $clist;

    }

}

class DTlocation extends JTable {

  var $id =null;

  var $name=null;

  var $address=null ;

  var $address2=null ;

  var $country=null ;

  var $phone=null ;

  var $email=null ;

  var $website=null ;

  var $city=null ;

  var $state=null ;

  var $zip=null ; 

  var $image=null ;

  var $showimage=null;

  function __construct( &$db = null ) {

    $db = &JFactory::getDBO();

    $this->db = $db ;

    parent::__construct( '#__dtregister_locations', 'id', $db );

  }

  function find($condition = ""){

    	if($condition != ""){

	     $where = " where ".$condition ;

	   }else{

	    $where = "";

	   }

	   $sql = "select * from #__dtregister_locations ".$where ." " ;

	   $this->db->setQuery($sql);

	   return  $this->db->loadObjectList(); 

  }

}

class DThistory extends JTable {

  var $id =null;

  var $type=null;

  var $amount=null ;

   var $payment_date=null ;

  var $user_id=null ;
  
  var $transaction_id = "" ;

  function __construct( &$db = null ) {

    $db = &JFactory::getDBO();

    $this->db = $db ;

    parent::__construct( '#__dtregister_history', 'id', $db );

  }

  function find($condition = ""){

    	if($condition != ""){

	     $where = " where ".$condition ;

	   }else{

	    $where = "";

	   }

	   $sql = "select * from #__dtregister_history ".$where ." " ;

	   $this->db->setQuery($sql);

	   return  $this->db->loadObjectList(); 

  }

}

class DT_User {

	var $id ;

	var $discount_code_id;

	function DT_User($id=null,$event_id=null){

		global $gid, $option;

		$database = &JFactory::getDBO();

		$this->db = &$database;

		if(isset($id)){

			$this->id = $id;

			 $query = "select * from #__dtregister_user where userId =".$this->id; 

			$this->db->setQuery($query);

			$data = $this->db->loadObjectList();

			foreach($data[0] as $key=>$value){
                
				$this->$key = $value;

			}
			
			if($this->user_id !="" && $this->user_id !=0){
			   $joomlauser = $this->get_joomla_user();
			   $this->username = $joomlauser->username ;
			}
			$this->barCodeHtml = $this->barCodeImg();
			$this->register_date = get_date_only($this->register_date);

		}

		if($event_id == "" &&  isset($this->eventId) && $this->eventId !=""){

			$event_id = $this->eventId ; 

		}

        if($event_id != ""){

		   $this->event = new Event($event_id);

           $this->eventId = $event_id;
		   
		   if(isset($id)){
		      $this->tax = numberFormat($this->taxAmount(),2);
		   
		   
		   
		       $this->amountNoTax = numberFormat($this->noTax(),2);
		   }

         }

	}
    
	function barCodeImg(){
	   
	   global $barCodeImagetypeToExt , $barcode_image_type ,$barcode_enable ;
	   $this->barcodePath = "";
	   if(!$barcode_enable){
		   
		   return '';
	   }else{
           $barcodePath =JURI::root( false )."images/dtregister/barcode/".$this->confirmNum.".".$barCodeImagetypeToExt[$barcode_image_type];
		   $this->barcodePath = $barcodePath;
           return $barcodeImg = '<img border="0" src="'.$barcodePath.'" />';
  
	   }
	   	
    }
	
	function taxAmount(){
	   	
		$amount = $this->get_amount();
	    if( $this->event->tax_enable){
			  $return  = $amount*$this->event->tax_amount/100 ;
			  
		}else{
		     $return = 0 ;	
		}
	   	
		return $return ;
		
	}
	
	function noTax(){
	   $amount = $this->get_amount();
	    if( $this->event->tax_enable){
			  $return  = $amount*100/($this->event->tax_amount + 100) ;
			  
		}else{
		     $return = $amount ;	
		}
	   	
		return $return ;
	}
	
	function saveJomsocialFields(){
	    global $map_joms_firstname , $map_joms_lastname , $map_joms_org , $map_joms_address , $map_joms_address2 ,$map_joms_city , $map_joms_state  , $map_joms_zip , $map_joms_country , $map_joms_phone , $cb_integrated ;
		
		$map_fields = array('org','address','address2','city','state','zip','country','phone');
		
		$map_dt_fields = array('userOrganization','userAddress','userAddress2','userCity','userState','userZip','userCountry','userPhone');
		
		foreach($map_fields  as $key=>$field){
		   $obj = new stdClass();
		   $obj->field_id = ${"map_joms_".$field} ;
		   $obj->user_id  = $this->user_id ;
		   if(isset($this->${$map_dt_fields[$key]})){
		      $obj->value = $this->${$map_dt_fields[$key]} ;
		   }else{
			  $obj->value = ""; 
		   }
		   $this->db->insertObject( '#__community_fields_values' , $obj );
		}
		
	}
	
	function loadJomsocial(&$object = null){
	  
	  $my = &JFactory::getUser();
	  global $map_joms_firstname , $map_joms_lastname , $map_joms_org , $map_joms_address , $map_joms_address2 ,$map_joms_city , $map_joms_state
	       , $map_joms_zip , $map_joms_country , $map_joms_phone , $cb_integrated ;
		   if($cb_integrated !=2){
		     return ;
		   }
	  if($my->id){
	     $query = "select * from #__community_fields_values where user_id= ".$my->id ;
		 $this->db->setQuery($query);
		 $fieldsdata = $this->db->loadObjectList();
		 
		 $userdata = array();
		 foreach($fieldsdata as $fielddata){
		    
		   	$userdata[$fielddata->field_id] = $fielddata->value ;
			
		 }
		 
		 $map_fields = array('firstname','lastname','org','address','address2','city','state','zip','country','phone');
		 
		 $map_fields = array('org','address','address2','city','state','zip','country','phone');
		
		 foreach($map_fields as $map){
		   
		    $this->$map   = isset($userdata[${"map_joms_".$map}])?$userdata[${"map_joms_".$map}]:'';
			$cbmap = $map;
			if($map=="org"){
			  $cbmap = "company";
			}
			if($map =="zip"){
			  $cbmap = "zipcode";
			}
			$object->$map =  isset($userdata[${"map_joms_".$map}])?$userdata[${"map_joms_".$map}]:'';
			$object->{"cb_".$cbmap} =  isset($userdata[${"map_joms_".$map}])?$userdata[${"map_joms_".$map}]:'';
		 }
		 
	  }
	      $query = "select * from #__users where id= ".$my->id ;
		  $this->db->setQuery($query);
		 $user_data = $this->db->loadObject();
		 $data = explode(" ",$user_data->name );
		 $object->firstname = $data[0];
		 
		 $object->lastname = (count($data)>1)?end($data):'';
	
	}

	function check_prerequisite($prerequisite,$registerations){
	   
	   $prerequisite_id =  array();
				foreach($prerequisite as $evet){
				   $prerequisite_id[$evet->prerequisite_id] = $evet->prerequisite_id;
				}
	 
	   foreach($registerations as $reg){
	       
	       if(isset($prerequisite_id[$reg->eventId])){
		     unset($prerequisite_id[$reg->eventId]);
		   }
	   }
	  
	   return (count($prerequisite_id)==0);
	   
	}
	
	function check_prerequisite_cat($prerequisite,$registerations){
	   
	    $prerequisite_id =  array();
		foreach($prerequisite as $evet){
		   $prerequisite_id[$evet->prerequisite_id] = $evet->prerequisite_id;
		}
		$return = false ;
		foreach($registerations as $reg){
	       
		   $evt = new Event($reg->eventId);
		 
		   if(in_array($evt->category,$prerequisite_id)){
		   
		     $return = true ;
			 break ;
		   }
	       
	    }
		
		return $return ;
	   
	}
	
	function check_overlap($event,$registerations){
	   
	   $overlap = false ;
	 
	   foreach($registerations as $reg){
	      $evet = new Event($reg->eventId);
		  if($evet->summary=="" || $evet->excludeoverlap ){
		      continue;
		  }
		  
		 // echo "<br />(".$evet->dtstart." >= ".$event->dtstart." &&  ".$event->dtstart." <= ".$evet->dtend.")||(".$evet->dtstart." >= ".$event->dtend." && ".$event->dtend." <= ".$evet->dtend.")";
		  if(($evet->dtstart <= $event->dtstart &&  $event->dtstart <= $evet->dtend)||($evet->dtstart <= $event->dtend && $event->dtend <= $evet->dtend)){
		      $overlap =  true ;
			  break ;
			  
		  }
		 
	   }
	   
	   return $overlap ;
	  
	}
     function set($data){
	   
	   $compare = array('firstname','lastname','organization','address','city','state','zip','country','email','phone','title','address2');
	   $asso_fileds = array('userFirstName','userLastName','userOrganization','userAddress','userCity','userstate','userZip','userCountry','userEmail','userPhone','userTitle','userAddress2');
	   $fields = $this->db->getTableFields('#__dtregister_user');
	   foreach($compare as $key => $value){
	      if(isset($data[$value])){
		     $this->{$asso_fileds[$key]} = $data[$value];
		  }
	   }

	   foreach($fields['#__dtregister_user'] as $field=>$type){
	       
		   if(isset($data[$field])){
		     if(is_array($data[$field])){
			    $data[$field] = implode(",",$data[$field]);
			 }
			 $this->$field = $data[$field];
		  }else{
		     
		  }
	   }
	   
	}
	function save_billing_info(){

		$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');

		$this->save_field('billing_firstname',$billing_firstname);

		$this->save_field('billing_lastname',$billing_lastname);

		$this->save_field('billing_address',$billing_address);

		$this->save_field('billing_city',$billing_city);

		$this->save_field('billing_state',$billing_state);

		$this->save_field('billing_zipcode',$billing_zipcode);

		$this->save_field('billing_email',$billing_email);

	}
    
	function save($data){
	  
	    $fields = $this->db->getTableFields('#__dtregister_user');
		foreach($fields['#__dtregister_user'] as $field=>$type){
	      if(isset($data->$field)){
			  if($field == "register_date"){
				   continue ;
			  }
		     echo "<br />".$sql = "update #__dtregister_user set $field='".$data->$field."' where userId=".$this->id ;
			 $this->db->setQuery($sql);
			 $this->db->query();
			echo "<br />". $this->$field = $data->$field ;
		  }else{ 
		     
		  }
	   }
	  
	}

	function save_field($field,$value){

		$query = "update #__dtregister_user set ".$field."=".$this->db->Quote($value)." where userId =".$this->id;

		$this->db->setQuery($query);

		$this->db->query();

	}

    function  get_cb_user(){

	$query = "select * from #__comprofiler where approved=1 and avatarapproved=1 and user_id=".$this->user_id;

	 $this->db->setQuery($query);

	return  $this->db->loadObject();

    }
	
	function  get_jomsocial_user(){

	$query = "select * from #__community_users where userid=".$this->user_id;

	 $this->db->setQuery($query);

	return  $this->db->loadObject();

    }

	 function  get_joomla_user($user_id=null){

			$query = "select * from #__users where  id=".$this->user_id;

	 	$this->db->setQuery($query);

		return  $this->db->loadObject();

	 }
    
	function userRegistration($username,$password){
	    
		  global $cb_integrated , $usercreation ;
		  $user = &JFactory::getUser();
		  if($user->id  || $username=="" || $password ==""){
		     return ;
		  }
		  $joomlaUser =  false ;
		  if($usercreation){
			  $joomlaUser = $this->createJoomlaUser($username,$password) ;
		   }
		   if($cb_integrated ==2){
		      if($joomlaUser){
			     $this->createJomsocilaUser();
			  }
		   }elseif($cb_integrated ==1){
		      if($joomlaUser){
			     $this->createCbUser();
			  }
			  
			  
			  
		   }
		
		
	   
	}
	
	function generateconfirmNum(){
	   
	   global $confirm_number_type , $confirm_number_prefix , $confirm_number_start ;
	   
	   if($confirm_number_type=='random'){
	       $chars = "0123456789";

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

			for($i=0; $i<7; $i++){
	
				$x_invoice_num1 .= $chars[rand()%strlen($chars)];
	
			}

           
	   }else{
	       $x_invoice_num1 = $confirm_number_start+1 ;
	   }
	   
	   return $this->confirmNum = $confirm_number_prefix.$x_invoice_num1 ;
	   
	   
	   
	}
	
    function createJoomlaUser($username,$password){
	   global $mainframe;
	   $user 		= clone(JFactory::getUser());
	   $pathway 	=& $mainframe->getPathway();
	   $config		=& JFactory::getConfig();
	   $authorize	=& JFactory::getACL();
	   $document   =& JFactory::getDocument();
	   $usersConfig = &JComponentHelper::getParams( 'com_users' );
	   if ($usersConfig->get('allowUserRegistration') == '0') {
			
		 	return false;
	   }
	   $newUsertype = $usersConfig->get( 'new_usertype' );
	   if (!$newUsertype) {
			$newUsertype = 'Registered';
	   }
	   jimport('joomla.user.helper');
	   $salt  = JUserHelper::genRandomPassword(32);
	   $crypt = JUserHelper::getCryptedPassword($password, $salt);
	   $password = $crypt.':'.$salt;
	   $user->set('id', 0);
	   $user->set('username', $username);
	   $user->set('password', $password);
	   $user->set('usertype', $newUsertype);
	   $user->set('email' , $this->userEmail);
	   $user->set('name' , $this->userFirstName." ".$this->userLastName);
	   $user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));

	   $date =& JFactory::getDate();
	   $user->set('registerDate', $date->toMySQL());
	   if ( !$user->save() ){
			return false;
		}else{
		    $this->user_id = $user->id ;
		    $this->save_field('user_id',$user->id);
		    return true ;
		}
	   
	}
	
	function createCbUser(){
	    
		$obj = new stdClass(); 
		$obj->id = $this->user_id ; $obj->user_id = $this->user_id ;
		$obj->firstname 	= $this->userFirstName ;
		$obj->lastname 	= $this->userLastName 	 ;
		$obj->cb_company 	= $this->userOrganization 	 ;
		$obj->cb_address 	= $this->userAddress 	 ;
		$obj->cb_phone 	= $this->userPhone 	 ;
	    $obj->cb_city 	= $this->userCity 	 ;
		$obj->cb_state 	= $this->userState 	 ;
		$obj->cb_zipcode 	= $this->userZip 	 ;
		$obj->cb_country 	= $this->userCountry 	 ;
		$obj->cb_address2 	= $this->userAddress2 		 ;
		$obj->cb_title 	= $this->userTitle 	 ;
		
		$this->db->insertObject( '#__comprofiler' , $obj );
		
	}
	
	function createJomsocilaUser(){
	     
		 global $map_joms_firstname , $map_joms_lastname , $map_joms_org , $map_joms_address , $map_joms_address2 ,$map_joms_city , $map_joms_state , $map_joms_zip , $map_joms_country , $map_joms_phone , $cb_integrated ;
		  $obj = new stdClass();

						
           require_once( JPATH_BASE .  '/components/com_community/libraries/core.php');
						
            $config	=& CFactory::getConfig();
			$obj->userid	= $this->user_id;
    		// Load default params				

		   $obj->params = "notifyEmailSystem=" . $config->get('privacyemail') . "\n"

									 . "privacyProfileView=" . $config->get('privacyprofile') . "\n"

									 . "privacyPhotoView=" . $config->get('privacyphotos') . "\n"

									 . "privacyFriendsView=" . $config->get('privacyfriends') . "\n"

									 . "privacyVideoView=1\n"

									 . "notifyEmailMessage=" . $config->get('privacyemailpm') . "\n"

									 . "notifyEmailApps=" . $config->get('privacyapps') . "\n"

									 . "notifyWallComment=" . $config->get('privacywallcomment') . "\n";

						
            $obj->avatar = 'components/com_community/assets/default.jpg';
			$obj->thumb  = 'components/com_community/assets/default_thumb.jpg';
			$this->db->insertObject( '#__community_users' , $obj );
			if(!$this->db->getErrorNum()){

			   $this->saveJomsocialFields();

		    }

		 
	}
    
function calculate_fee($memtot,$userid,$code){

			$this->fee = $this->event->get_fee($memtot,$userid);	

			if($this->set_discount_code($code)){

				$this->discount_code_amount = $this->discountcode->get_discount_amount($this->fee);

				if($this->discount_code_amount == $this->fee){

					$this->payment_type  = 'Free';

				}

				$this->fee  -= $this->discount_code_amount;

			}

		}

	function validate_code($code){
            global $now ;
			if($code==""){

			  return false ;

			}

			$dt_code =  new DiscountCode();

			$code = $dt_code->getcodes('code="'.$code.'"');

            if(!isset($code[0]->id)){

			   $this->discountcode->error = JText::_( 'DT_CODE_INCORRECT' ) ;

			   return false;

			}else if($code[0]->publish != 1){

			    $this->discountcode->error = JText::_( 'DT_CODE_NOT_AVAILABLE' ) ;

			   	return false;

			}

			$this->discount_id = $code[0]->id;

			$this->discountcode = new DiscountCode($this->discount_id);

			if($this->discountcode->limit > 0 && ($this->discountcode->limit <= $this->discountcode->used())){

			   $this->discountcode->error = JText::_( 'DT_CODE_NOT_AVAILABLE' ) ;

			   return false ;

			}

            $date =& JFactory::getDate();

		     $query = "select * from #__dtregister_events_codes as edc inner join #__dtregister_codes as dc on dc.id = edc.discount_code_id 

		          and edc.event_id = ".$this->eventId." where dc.code='".$code[0]->code."' and dc.publish=1 and '".$date->toFormat()."' between dc.start and dc.end ";

                 $query = "select * from #__dtregister_events_codes as edc inner join #__dtregister_codes as dc on dc.id = edc.discount_code_id 

		          and edc.event_id = ".$this->eventId." where dc.code='".$code[0]->code."' and dc.publish=1 and '".$now->toFormat()."' between dc.start and dc.end ";

				  $this->db->setQuery($query);

				  $this->db->query();

             if($this->db->getNumRows() > 0){

				return true;

			 }else{

			    $this->discountcode->error = JText::_( 'DT_CODE_EXPIRED' ) ;

			    return false ;

			 }

				 // return ($this->db->getNumRows() > 0 );

	}

	function set_discount_code($code){

		if($this->validate_code($code)){

			$dt_code =  new DiscountCode();

			$code = $dt_code->getcodes('code="'.$code.' "');

			$this->discount_id = $code[0]->id;

			unset($dt_code);

			$this->discountcode = new DiscountCode($this->discount_id);

			return true ; 

		}else{

			$this->discount_id = 0;

			return false;

		}

	}

	function get_custom_fee($user=null,$members=null){
	    if($user== ""){
		   $user = $this;
		}
		$type='I';
		if($this->userType == 'G'){
		   $type = "B";
		}
        $fee = $this->event->get_custom_fields_fee((array)$user,$type);
		if($this->userType == 'G'){
		   if($members == ""){ 
		     $members = $this->get_members();
		   }
		   foreach($members  as $member){
			   if(!isset($member->remove) || $member->remove !=1)
		      $fee += $this->event->get_custom_fields_fee((array)$member,'M');
		   }
		}
		return $fee ;
	}

	function add_code(){

		$query = "update #__dtregister_user set discount_code_id='".$this->discount_id."' where userId =".$this->id;

		$this->db->setQuery($query);

		$this->db->query();

	}

	function get_members(){

			  $query = "select * from #__dtregister_group_member as gm  inner join #__dtregister_group as g on g.groupId= gm.groupUserId  where g.useid =".$this->id;

			$this->db->setQuery($query);
            
			  $this->db->getErrorMsg();
			
			return $this->db->loadObjectList();

	}

	function get_contact_details(){
        $details[] = $this->userAddress ;
		$details[] = $this->userAddress2 ;
		$details[] = $this->userCity.', '.$this->userState.' '.$this->userZip;
		$details[] = $this->userCountry ;
		$details[] = $this->userPhone ;
		$details[] = $this->userEmail ;
		$details = array_filter($details);
		return implode("<br />",$details);
		return  $this->userAddress.'<br />'.$this->userCity.', '.$this->userState.' '.$this->userZip.'<br />'.$this->userPhone.'<br />'.$this->userEmail;

	}

	function get_name(){

		return  $this->userFirstName.' '.$this->userLastName;

	}

	function get_group_names(){
        
		if($this->userType=='I'){
		   	
			
			return  $this->userFirstName.' '.$this->userLastName;
			
		}
	   
		$members = $this->get_members();

		$mem_str  = "";

		if(is_array($members))

		foreach($members as $key=>$member){

			$mem_str .= $member->firstname." ".$member->lastname."<br />";

		}

		return $mem_str ;

	}

	function get_contact_custom_fields(){

	       $fields = $this->event->get_fields();

		   $contactCustomFields = "";

		   if(is_array($fields))

		   foreach($fields as $field){

				if($this->{$field->name}=="" && $field->type != 6){

					continue;

				}
                if($field->type== 6){
					$contactCustomFields .= $field->textual.'<br />';
				}else{
					$contactCustomFields .= $field->label.': '.$this->{$field->name}.'<br />';
				}
				

		   }

		   return $contactCustomFields ; 

	}

	function get_group_custom_fileds(){

		$members = $this->get_members();

		$fields = $this->event->get_fields();

		$str  = "";

		if(is_array($members))

		foreach($members as $key=>$member){

			 if(is_array($fields))

		   		foreach($fields as $field){

					if($member->{$field->name}=="" && $field->type != 6){

						continue;

					}
                    if($field->type == 6){
						$str .= $field->textual.'<br />';
					}else{
					   $str .= $field->label.': '.$member->{$field->name}.'<br />';	
					}
				  

		   	   }

		}

		return $str ;

	}

	function get_details(){

		 $query = "select * from   #__dtregister_group as g inner join #__dtregister_group_amount as a on g.groupId= a.groupId  where g.useid =".$this->id;

			$this->db->setQuery($query);

			return $this->db->loadObject();

	}

	function set_amount($amount){
         
		 $amount =  str_replace(",",".", $amount) ;
		 $query = "select * from #__dtregister_group_amount as gm inner join #__dtregister_group as g on g.groupId= gm.groupId  where g.useid =".$this->id;

			$this->db->setQuery($query);

            $this->db->query();

			if($this->db->getNumRows()>0){

			    // insert

			    $gid = $this->getGroup();

				$query = "update #__dtregister_group_amount set amount='$amount' where groupId = '$gid' ";

				//update

			}else{

			    // insert

			    $memtot = count($this->get_members());

				$gid = $this->getGroup();

			    $query = "insert into  #__dtregister_group_amount set amount='$amount' , numberOfPerson = '$memtot' , groupId = '$gid' ";

			}

			$this->db->setQuery($query);

			$this->db->query();

	}

	function getGroup(){

		    $query = "select groupId from #__dtregister_group  where useid =".$this->id;

			$this->db->setQuery($query);

			return $this->db->loadResult();

	}
	function find($condition="",$orderBy=null,$limitstart=null,$limit=null){
	    if($condition != ""){
		  $where = " where ".$condition ;
		}else{
		  $where = "";
		}
		/// #__dtregister_group g inner join #__dtregister_group_amount a on g.groupId= a.groupId
		$sql = "Select SQL_CALC_FOUND_ROWS * from #__dtregister_user as u inner join #__jevents_vevdetail as je on je.evdet_id = u.eventId inner join 
		        #__dtregister_group as g on g.useid = u.userId inner join #__dtregister_group_amount as a on g.groupId = a.groupId 
		  ".$where."  ORDER BY $orderBy ";
		$this->db->setQuery($sql,$limitstart,$limit);
		
		//echo $this->db->getQuery();
		//echo "<br />".$this->db->getErrorMsg();
		return $this->db->loadObjectList();
		
	}
    
	function is_payable(){
	    
		include (JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
	    $this->event->over_ride_global();
		 $arrPaymentMethods=explode(",",$paymentmethod);
	    if(count($arrPaymentMethods) == 1 && in_array('pay_later',$arrPaymentMethods)){
	     
		  return false ;
		 
	    }else{
		   
		   return true ;
		   
		}
	
	}
	
    function is_editable(){
	   
	   global $now ;
	   include (JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
	   
	  $this->event->over_ride_global();
	  $is_passed = $this->event->is_passed() ;
	    $arrPaymentMethods=explode(",",$paymentmethod);
	    if(count($arrPaymentMethods) == 1 && in_array('pay_later',$arrPaymentMethods)  && !$is_passed){
	     
		 $totamount = $this->get_amount();
		 $change_fee = change_fee($totamount);
		 if($change_fee <= 0){
		  
			return true ;
		  
		 }else{
			
			return false ;
			
		 }
		 
	  }
	  
	   if($this->event->change_date =="" || $this->event->change_date =="0000-00-00"){
	     $this->event->change_date = strtotime($now->toFormat('%Y-%m-%d')." +1 day");
	  }else{
	     $this->event->change_date = strtotime($this->event->change_date);
	  }
	  if($this->event->change_date < $now->toUnix(true)){
	      return false ;
	  }
	   if($is_passed || $this->event->cutoff_passed() || $this->cancel==1 || $this->event->edit_fee==0
	   ){
	     return false;
	   }else{
	     return true ;
	   }
	   
	}
	
	 function is_cancelabelable(){
	  
	 global $now ;
	 
      include (JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
	   
	  $this->event->over_ride_global();
	 
	  $arrPaymentMethods=explode(",",$paymentmethod);
	  $this->event->resume_global();
	  if($this->cancel == 1){
	    return false ;
	  }
	  if(count($arrPaymentMethods) == 1 && in_array('pay_later',$arrPaymentMethods) && !$is_passed){
	     
	     $totamount = $this->get_amount();
         $cancel_amount = cancel_fee($totamount);
		 if($cancel_amount <= 0){
		  
		    return true ;
		  
		 }else{
		    
			return false ;
			
		 }
	     
	  }
	 
	  if($this->event->cancel_date ==""){
	     $this->event->cancel_date = strtotime($now->toFormat('%Y-%m-%d')." +1 day");
	  }else{
	     $this->event->cancel_date = strtotime($this->event->cancel_date);
	  }
	  //echo "<br>".$this->event->cancel_date." > ".strtotime("today")." && ".$this->event->cancelfee_enable." && ".$this->cancel ;
	  if($this->event->cancel_date >= $now->toUnix(true) && $this->event->cancelfee_enable ==1 && $this->cancel != 1 && !$is_passed){
	     return true ; 
	  }else{
	     return false ;
	  }
	   
	}
	
	function get_amount(){
	   
	   $query = "select gm.amount from #__dtregister_group_amount as gm inner join #__dtregister_group as g on g.groupId= gm.groupId  where g.useid =".$this->id;
	   $this->db->setQuery($query);
	   return $this->db->loadResult();
	   
	}

}

class DiscountCode{

	var $id ;

	var $name;

	var $label;

	var $publish;

	var $discount_type;

	var $start;

	var $end;

	var $amount;

	var $code;
	
	var $events_enable;

	var $fields = array('name','publish','discount_type','start','end','amount','code','limit','events_enable');

	function DiscountCode($id=null){

		global $database, $gid, $option;

		$database = &JFactory::getDBO();

		$this->db = &$database;

		if(isset($id) && $id > 0){

			$this->id = $id;

			$query = "select * from #__dtregister_codes  where id =".$this->id;

			$this->db->setQuery($query);

			$data = $this->db->loadObjectList();

			foreach($data[0] as $key=>$value){

				$this->$key = $value;

			}

		}

	}

	function set($data=array()){

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

			if(in_array($key,$this->fields)){

				$this->$key = $value;

			}

		}

	}

	function save(){

		foreach($this->fields as $value){

			$fields[] .= "`".$value."` = '".$this->$value."'";

		}

		if(!isset($this->id)){

			$query = "insert #__dtregister_codes set "	;

			$where = "";

		}else{

			$query = "update #__dtregister_codes set "	;

			$where = " where id=".$this->id;

		}

	    $query .= implode("," ,$fields);

		$this->db->setQuery($query.$where);

		$this->db->query();
		if(!isset($this->id)){
		   $this->id = $this->db->insertid();
		}
		
		if($this->events_enable == 1){
		   
		   $this->enableAllEvents();
		   
		}

	}

    function enableAllEvents(){
	   
	   $query = " SELECT DISTINCT e.eventId
					FROM #__dtregister_group_event as e
					LEFT JOIN #__dtregister_events_codes as d ON e.eventId = d.event_id
					AND d.discount_code_id = ".$this->id."
					WHERE e.publish =1
					AND d.event_id IS NULL ";
	   
	   $this->db->setQuery($query);		
	   $data = $this->db->loadRowList();
	   
	   foreach($data as $evtid){
	      
		  $value = $evtid[0];
	      $query = "insert #__dtregister_events_codes set event_id =".$value.", discount_code_id =".$this->id;
		  $this->db->setQuery($query);		
		  $this->db->query();		
	         
	   }
	   
	}

	function  get(){

		return $this;

	}

	function getcodes($condition=null){

		$query = "select * from #__dtregister_codes";

		if(isset($condition)){

			$query .= " where ".$condition;	

		}

		$this->db->setQuery($query);

		 return $this->db->loadObjectList();

	}

	function check_space($name){

		if(preg_match("/[ ]/", $name)){

			$this->error = "Spaces are not allowed in the field name. Your space has been replaced by a _ character";

			return false;

		}

		return true;

	}

	function validate_name($name){

		if($name==""){

			$this->error = "Name is required";

			return false;

		}

		if(preg_match("/[^a-zA-Z0-9_]/", $name)){

			$this->error = "Field name only allow characters a-z,A-Z,0-9 and '_' character";

			return false;

		}

		return true;	

	}

	function validate_code($code){

		$query = "select * from #__dtregister_codes";

			$query .= " where code='".$code."'";	

		if(isset($this->id)){

			$query .= " and id <> ".$this->id;

		}

		$this->db->setQuery($query);

		$this->db->query();

		return ($this->db->getNumRows() == 0 );

	}

	function delete(){

		$query = "delete from #__dtregister_codes where id =".$this->id;

		$this->db->setQuery($query);

		$this->db->query();

	}

	function get_discount_amount($amount){

		if($this->discount_type==1){

			if($this->amount < $amount){

				return $this->amount;

			}else{

				return $amount;

			}

		}else{

			$percentage = $this->amount/100;

			return ($amount*$percentage);

		}

	}

	function used(){

	   $query = "select sum(1) from 
	   #__dtregister_user a 
	   inner join #__jevents_vevdetail d  on a.eventId=d.evdet_id 
	   inner join  #__dtregister_group b on  a.userId= b.useid 
	   
       inner join #__dtregister_group_event evt  on evt.eventId = d.evdet_id 
 where a.cancel <> 1 and a.discount_code_id=".$this->id." group by discount_code_id ";

	   $this->db->setQuery($query);
      // echo "<br />". $this->db->getQuery();
	 //  echo "<br />";
	   $this->uses = $this->db->loadResult();

	   return $this->uses ;

	}

}

class Custom_field {

	function Custom_field($id = ""){
        $this->id = 0 ;
	    if($id !=""){

		  $this->id = $id ;

		}

        $database = &JFactory::getDBO();

		$this->db = &$database;

	}

	function getfields($condition = ""){

	   if($condition != ""){

	     $where = " where ".$condition ;

	   }else{

	    $where = "";

	   }

	   $sql = "select * from #__dtregister_fields ".$where ." order by ordering" ;

	   $this->db->setQuery($sql);

	   return  $this->db->loadObjectList(); 

	}
    function read(){
	  $sql = "select * from #__dtregister_fields where id='".$this->id."' order by ordering" ;
	   $this->db->setQuery($sql);

	   $data = $this->db->loadObject();
	  echo  $this->db->getErrorMsg();
	  if(is_object($data))
	   foreach($data as $key=>$value){
	     $this->$key = $value;
	   }
	   
	}

	function formhtml($obj=null,$event=null,$form='',$overlimitdisable=false){
	 
	  $serialobj = base64_encode(serialize($obj));
	 
	  $this->read();
	  $new_line=$this->new_line;
	  $this->javascript = "";
	  $this->selected = stripslashes($this->selected);
	  $this->javascript_valid_data = " ";
	  $this->label = addslashes($this->label);
	  $this->childJs = "";
	  $document =& JFactory::getDocument();
	  if($this->hasChild()){
	    // trigger the ajax ;
		
		 $document->addScript( JURI::root(true)."/components/com_dtregister/assets/js/jquery.js");
		ob_start();
		if(!isset($_REQUEST['obj'])){
		   ?>
            var not_remove = [];
              
            DTjQuery(function(){
           <?php
		}
		?>
          
          <?php
		 
          if($this->type == '1'){
		    $field_js_event = "change";
		    ?>
              
              DTjQuery("#Field<?php echo $this->id; ?>").live('change',function(){
            <?php
		  }else{
		     if($this->type==3){
			     $field_js_event = "click";
			 }else{
			     $field_js_event = "change";
			 }
		     
		    ?>
            
			 DTjQuery("#Field<?php echo $this->id; ?>").live('<?php echo $field_js_event; ?>',function(){
               if(this.checked){
                 this.selectedIndex = DTjQuery('input[id="Field<?php echo $this->id;?>"]').index(this) ;
               }else{
                 this.selectedIndex= '';
               }
                DTjQuery.each(DTjQuery('input[id="Field<?php echo $this->id;?>"]'),function(i){
                   
                   if(this.checked){
                      not_remove.push(i);
                    
                     
                   }
                   
                   
               });
              
			<?php
		  }		  
		  ?>
		       
               
               DTjQuery.ajax({
                  type :'POST',
                  dataType :'html',
                  url : '<?php echo JRoute::_('index.php',false) ?>',
                  context : this ,
                  data :{no_html:1,field_id:<?php echo $this->id;?>,selection:this.selectedIndex,option:'com_dtregister',not_remove:not_remove,task:'getconditonField',eventId:<?php echo  $event->id; ?>,obj:"<?php echo $serialobj; ?>"},
                  success:function(data){
                   
                    var scriptdata = "";
                     for (i=0; i < data.length; i++) {
                        if(data.charAt(i)=="\/"){
                           if(data.substr(i,15)=="\/*DTendScript*\/"){
                              break;
                           }else{
                              scriptdata +=data.charAt(i) ;
                           }
                        }else{
                           
                           scriptdata +=data.charAt(i) ;
                        }
                        
                        }
                     
                   
                   eval(scriptdata);
			
                    
                     var DT_field = this ;
                     
                     DTjQuery.each(elements,function(t,j){
                        
                      
                         
                         if(DTjQuery("#Field"+t).size()==0){
                           
                           parentf = insertorder(DTjQuery(DT_field).parent().parent(),t);
                           parentf.after(j);
                           JTooltips = new Tips($$('.FieldTip'+t), { maxTitleChars: 50, fixed: false});
                           
                           if(DTjQuery("#Field"+t).attr('type')=='radio' || DTjQuery("#Field"+t).attr('type')=='checkbox'){
                                 
                               
                                 DTjQuery('input[id="Field'+t+'"]:checked').each(function(){
                                     DTjQuery(this).trigger('change');
                                 });
                                 
                           }else{
                               
                               DTjQuery("#Field"+t).trigger('change');
                               
                           }
                           
                          }
                       
                        
                     });
                     function insertorder(parentf,field_id){
                        var beforefield = [] ;
                        DTjQuery.each(ordering,function(k,v){
                             
                             if(field_id==k){
                                return false ;
                             
                             }
                             beforefield.push(k);
                             
                                                         
                                 
                        });
                       
                       var reversefields = beforefield.reverse() ;
                       
                        DTjQuery.each(reversefields,function(k,v){
                            
                            if(DTjQuery("#Field"+v).size()>0){
                               parentf =  DTjQuery("#Field"+v).parent().parent();
                               return false ;
                            }
                           
                            
                        });
                        
                        return parentf ;
                     }
                      DTjQuery(remove_elements).each(function(i,j){
                        
                        for(var t in j){
                         
                          if(DTjQuery("#Field"+t).size() > 0){
                            DTjQuery("#Field"+t).parent().parent().remove();
                           
                          }
                        }
                        
                     });
                     
                     not_remove = [] ;
                    
                  }
                  
               });
                
                 
			  });
			   
		  <?php
		  if(!isset($_REQUEST['obj'])){
		    
		   ?>
            
             <?php
           if($field_js_event=='click' || $this->type==4){
			  ?>
               DTjQuery.each(DTjQuery('input[id="Field<?php echo $this->id;?>"]:checked'),function(){
                   
                   DTjQuery(this).trigger('<?php echo $field_js_event; ?>');
                   <?php
					  if($this->type == 3){
					  				 
					?>
                    if(DTjQuery(this).attr('checked')){
                 
                       DTjQuery(this).removeAttr('checked');
                    }else{
                       DTjQuery(this).attr('checked',true);
                    }
                    <?php
					}
					?>
               });
               
              <?php  
			}else{
			  ?>
			    DTjQuery("#Field<?php echo $this->id; ?>").trigger('<?php echo $field_js_event; ?>');
               
            <?php
			}
             ?>
             })
           
           <?php } ?>
		  <?php 
		  $js =  ob_get_clean();
		  $this->childJs = $js ;
		 $document->addScriptDeclaration( $js );
		 
		
	 }
	  
	  switch($this->type){
	     case 0:
             //Text box
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
			 $this->javascript = "if ( typeof(document.frmcart.{$this->name}) != 'undefined' && document.frmcart.{$this->name}.value == ''){
                                       alert('{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')." ');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    }";
									$maxlength = ($this->maxlength !=0 && $this->maxlength=="")?"maxlength='".$this->maxlength."'":'';
             return "<input type='text' id='Field".$this->id."' class='inputbox' size='$this->field_size' $maxlength name='$this->name' value='$value' />" ;
         break;
		 case 1:
                //Drop down
				
			  $this->optionlimit = $this->get_option_limit($event->id);
              $this->optionused = $this->option_usage($event->id,$obj);
			  $fieldSize=$this->field_size;
              $dropDownDatas=explode("|",$this->values);
              $options=array();
			  		  
			  $options[]=JHTML::_('select.option',null,JText::_( 'DT_SELECT_ONE' ));
			  $value = isset($obj->{$this->name})?$obj->{$this->name}:$this->selected;
              for($i=0,$n=count($dropDownDatas);$i<$n;$i++){
                 if(!is_array($this->optionlimit) ||(isset($this->optionlimit[$i]) && $this->optionlimit[$i]==0 ) ){
                      
					 $options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]));
                 }else{
                      if($this->optionlimit[$i] > $this->optionused[$i] ){
                          $options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]));
					  }else{
					       $disabled = false ;
						   if($overlimitdisable){
							  $disabled = true;
							  if(trim($dropDownDatas[$i])==$value){
							     $disabled = "" ;
							  }
							  $options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]),'value', 'text',$disabled);
						   }else{
							  continue ;
						   }
						  
					  }

			     }
                 	//$options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]));
               }
			    $this->javascript = "if (typeof(document.frmcart.{$this->name}) != 'undefined' && document.frmcart.{$this->name}.value == ''){
                                       alert('{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')."');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    }";
								
              return JHTML::_('select.genericlist', $options,$this->name,"style='width:".$fieldSize."px' class='inputbox' ","value","text",$value,"Field".$this->id) ;
    	 break;
		 case 2:
               //Text area
			    $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
				$this->javascript = "if (typeof(document.frmcart.{$this->name}) != 'undefined' && document.frmcart.{$this->name}.value == ''){
                                       alert('{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')."');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    }";
				 $maxlength = ($this->maxlength=="")?-1:$this->maxlength ;
				 $counter = "" ;
				 if($this->fee_field){
					  if($this->showcharcnt){
						  
						  $displayFormat = " , displayFormat : '#input ".JText::_('DT_CHARACTERS')."' ";
						  
					  }else{
						  $displayFormat = " , displayFormat:''" ;
					  }
					 ob_start();
					 ?>
                     <script type="text/javascript">
				    var options = {   'originalStyle': 'originalDisplayInfo' ,'maxCharacterSize':<?php echo $maxlength ?> <?php echo $displayFormat?>  };  
                        DTjQuery('#Field<?php echo $this->id; ?>').textareaCount(options);  
					</script>
                     <?php
					$js = ob_get_clean();
					
					$counter = $js ;
					
					
				 }
				
               return "<textarea name='$this->name' class='inputbox' id='Field".$this->id."' rows=$this->rows cols=$this->cols>$value</textarea>\n".$counter ;
         break;
		 case 3:
              //Checkbox
			  
			 $this->optionlimit = $this->get_option_limit($event->id);
             $this->optionused = $this->option_usage($event->id,$obj);
             $dropDownDatas=explode("|",$this->values);
			 
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:$this->selected;
			 if(strpos($value,',')){
				 $arrValues=explode(",",$value);
			 }else{
                $arrValues=explode("|",$value);
			 }
			
            //Trim the space
             for($i=0,$n=count($arrValues);$i<$n;$i++){
                 $arrValues[$i]=trim($arrValues[$i]);
             }
             //Get custom data
             $outPut="";
             for($i=0,$n=count($dropDownDatas);$i<$n;$i++){
			      $disabled = "";
                  if(isset($this->optionlimit[$i]) && $this->optionlimit[$i]!=0 && $this->optionlimit[$i] <= $this->optionused[$i]){
                       //continue ;
					   if($overlimitdisable){
					      $disabled = "disabled";
					   }else{
					      continue ;
					   }
					   
                  }
                  $data=trim($dropDownDatas[$i]);
                  if(in_array($data,$arrValues)){ $disabled = "" ;
                     if($new_line)
                         $outPut.="<input id='Field".$this->id."' name='$this->name[]' ".$disabled." class='inputbox' value='".htmlentities($data, ENT_QUOTES,'UTF-8')."' checked type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                     else
                          $outPut.="<input id='Field".$this->id."' name='$this->name[]' ".$disabled." class='inputbox' value='".htmlentities($data, ENT_QUOTES,'UTF-8')."' checked type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                   }else{
                        if($new_line)
                           $outPut.="<input id='Field".$this->id."' name='$this->name[]' ".$disabled." class='inputbox' value='".htmlentities($data, ENT_QUOTES,'UTF-8')."' type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                        else
                           $outPut.="<input id='Field".$this->id."' name='$this->name[]' ".$disabled." class='inputbox' value='".htmlentities($data, ENT_QUOTES,'UTF-8')."' type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                    }
             }
			 $values=explode("|",$this->values);
             $totalValues=count($values);
			
			$this->javascript ="var success=false;
                                  DTjQuery('input[id=\"Field".$this->id."\"]').each(function(index){
								       
									   if(this.checked){
									      success = true ;
										  return false ;
									   }
								       
								   }); 
                                   if(DTjQuery('input[id=\"Field".$this->id."\"]').size() > 0 && !success){
                                      alert(\"{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')."\");
                                      return;
                                   }";
			 
              return $outPut;
         break;
		 case 4:
             //Radio list
			 $this->optionlimit = $this->get_option_limit($event->id);
             $this->optionused = $this->option_usage($event->id,$obj);
             $dropDownDatas=explode("|",$this->values);
			 
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:$this->selected;
             $arrValues=explode("|",$value);
			 //Trim the space
             for($i=0,$n=count($arrValues);$i<$n;$i++){
                  $arrValues[$i]=trim($arrValues[$i]);
             }
             //Get custom data
             $outPut="";
             for($i=0,$n=count($dropDownDatas);$i<$n;$i++){
                     $disabled = "";
                 if(isset($this->optionlimit[$i]) && $this->optionlimit[$i]!=0 && $this->optionlimit[$i] <= $this->optionused[$i]){
                      if($overlimitdisable){
					      $disabled = "disabled";
					   }else{
					      continue ;
					   }
                 }
                 $data=trim($dropDownDatas[$i]);
				 $data=htmlentities(stripslashes(trim($dropDownDatas[$i])),null,'UTF-8');
                 if(in_array($data,$arrValues)){ $disabled = "" ;
                      if($new_line) 
                         $outPut.="<input id='Field".$this->id."' name='$this->name' ".$disabled."  class='inputbox' value='$data' type='radio' checked id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                      else
                         $outPut.="<input id='Field".$this->id."' name='$this->name' ".$disabled."  class='inputbox' value='$data' type='radio' checked id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                 }else{
                     if($new_line)
                        $outPut.="<input id='Field".$this->id."' name='$this->name' ".$disabled." class='inputbox' value='$data' type='radio' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                     else
                        $outPut.="<input id='Field".$this->id."' name='$this->name' ".$disabled." class='inputbox' value='$data' type='radio' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                 }
             }
			 
			 $values=explode("|",$this->values);
             $totalValues=count($values);
			 $this->javascript ="var success=false;
			                       DTjQuery('input[id=\"Field".$this->id."\"]').each(function(index){
								       
									   if(this.checked){
									      success = true ;
										  return false ;
									   }
								       
								   }); 
                                   
                                   if(DTjQuery('input[id=\"Field".$this->id."\"]').size() > 0 && !success){
                                      alert(\"{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')."\");
                                      return;
                                   }";
			 
             return $outPut;
          break;
		 case 5:
              //Date custom fields
			 JHTML::_('behavior.calendar');
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
            $format = ($this->date_format !='')?$this->date_format:'%Y-%m-%d';
			//echo "<br />line 1580 date " .strftime( $format,strtotime($value));
            //$outPut = JHTML::_("calendar","$value",$this->name,$this->name,$format,"class=' text_area datetype1 ' ");
			
			$outPut = '<input id="Field'.$this->id.'" class="inputbox" type="text" name="'.$this->name.'"
 size="25" maxlength="25"
value="'.$value.'" />
<input type="button" class="button" value="..."
onclick="return showCalendar(\'Field'.$this->id.'\',\''.$format.'\');" />' ;
			$this->javascript = "if (typeof(document.frmcart.{$this->name}) != 'undefined' && document.frmcart.{$this->name}.value == ''){
                                       alert('{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')."');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    }";
			$this->date_val  = str_replace("-","\-",$this->date_format);
			$this->date_val = str_replace('%d','dd',$this->date_val);
			$this->date_val = str_replace('%m','mm',$this->date_val);
			$this->date_val = str_replace('%Y','yyyy',$this->date_val);						
			$this->javascript_valid_data = "\n if (document.frmcart.{$this->name}.value != '' && !document.frmcart.{$this->name}.value.match(dateregex{$this->name})){
                                       alert('{$this->label} ".JText::_( 'DT_INVALID_DATE' )." ".$this->date_val."');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    } \n ";
			
			/*$document->addScriptDeclaration('window.addEvent(\'domready\', function() {
			    setTimeout("document.frmcart.'.$this->name.'.value = \"'.$value.'\" ", 100);
			  
			});
			');*/
			
			$this->date_format;
			$this->date_regex  = str_replace(".","\.",$this->date_format);
			$this->date_regex  = str_replace("-","\-",$this->date_regex);
			$this->date_regex = str_replace('%d','[0-3]?[0-9]',$this->date_regex);
			$this->date_regex = str_replace('%m','[01]?[0-9]',$this->date_regex);
			$this->date_regex = str_replace('%Y','[12][90][0-9][0-9]',$this->date_regex);
			///^[0-3]?[0-9]\/[01]?[0-9]\/[12][90][0-9][0-9]$/
			
			$document->addScriptDeclaration(" var dateregex".$this->name."= /".$this->date_regex."/ ;" );
			
			return $outPut;
          break;
		  case 7:
		         $name =  $this->name ;
		         $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
				  $this->javascript = "if (typeof(document.frmcart.{$this->name}) != 'undefined' && document.frmcart.{$this->name}.value == ''){
                                       alert('{$this->label} ".JText::_('DT_ERROR_FIELD_REQUIRED')."');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    }";
				  return "<input id='Field".$this->id."' class='inputbox' name='file_$name' value='' type='file' /> <button filename='$name' class='upload' filetype='".$this->filetypes."' filesize='".$this->filesize."' >".JText::_( 'DT_UPLOAD' )."</button><input type='hidden' name='$name' id='$name' value='' />&nbsp;".$value;
				  
		  case 6:

             return '<span id="Field'.$this->id.'">'.stripslashes($this->textual)."</span>";
          }
	  
   }
   
   function addChildValidation($user,$event,$form,$overlimitdisable){
       
	   $childs = $this->getchild();
	   $this->ChildValidationJs = "";
	   foreach($childs as $child){
	       
		   $child =  new Custom_field($child->id);
		   $child->read();
		   if($child->required){
		        $child->formhtml($user,$event,$form,$overlimitdisable);
		   
		        $this->ChildValidationJs .= $child->javascript.$child->addChildValidation($user,$event,$form,$overlimitdisable) ;
		   }
		  
		   
		   
		   
		   
	   }
	   
	   return $this->ChildValidationJs ;
	   
   }
   
	function html($obj=null){
	  $this->read();
	  if($this->type!=6){
	    return $obj->{$this->name} ;
	  }else{
		  return $this->textual ;
	   }
	  return "";
	
	}

	function individual_option_usage($eventId = 0){

	  $type = $this->get_field('type');

	  if(in_array($type,array(1,3,4))){

		  $usagelimit = $this->get_field('usagelimit');

		  $values = $this->get_field('values');

		  $name = $this->get_field('name');

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

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

			 $used_individual[$key] = $this->option_usage_individual($value,$name,$eventId );

		  }

		  return $used_individual;

	  }

	}

	function group_option_usage($eventId =0){

	   $type = $this->get_field('type');

	  if(in_array($type,array(1,3,4))){

		  $usagelimit = $this->get_field('usagelimit');

		  $values = $this->get_field('values');

		  $name = $this->get_field('name');

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

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

			 $used_group[$key] = $this->option_usage_group($value,$name,$eventId );

		  }

		  return $used_group;

	  }

	}

	function get_option_limit(){

	    $type = $this->get_field('type');

	    if(in_array($type,array(1,3,4))){

		  $usagelimit = $this->get_field('usagelimit');

		  $usagelimit =  explode("|",$usagelimit);

		  return $usagelimit;

	  }

	}

	function option_usage($eventId =0){

	  $individual = $this->individual_option_usage($eventId );

	  $group = $this->group_option_usage($eventId );
      $usage = array();
	  
	  if(is_array($group ))

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

	    $usage[$key] = $value + $individual[$key];
		if(isset($_SESSION['register']['option_used'][$this->id][$key])){
		   
		   $usage[$key] += $_SESSION['register']['option_used'][$this->id][$key] ;
		}

	  }

	   return $usage ;

	}

	function option_usage_group($option,$field,$eventId ){

	   $option = $this->db->Quote("%".$option."%");

	    $query = "select * from #__dtregister_group_member as gm inner join #__dtregister_group as g on g.groupId= gm.groupUserId  inner join #__dtregister_user as u on u.userId = g.useid where gm.".$field." like ".$option." and u.payment_verified = 1  and u.eventId = ".$eventId." ";

		$this->db->setQuery($query);

		$this->db->query();

		return $this->db->getNumRows();

	}

	function option_usage_individual($option,$field,$eventId ){

	   $option = $this->db->Quote("%".$option."%");

	   	$query = "select * from #__dtregister_user where ".$field." like ".$option." and payment_verified = 1 and eventId = ".$eventId." ";

		$this->db->setQuery($query);

		$this->db->query();

		return $this->db->getNumRows();

	}

	function get_field($field){

		$query = "select  `".$field."` , id from #__dtregister_fields where id = ".$this->id . " limit 1"	;

		$this->db->setQuery($query);

		$this->$field = $this->db->loadResult();

		return $this->$field ; 

	}
	
	function find($where=""){
	    if($where!=""){
		  $condition = " where $where ";
		}
		$query = "select  *  from #__dtregister_fields $condition "	;
		$this->db->setQuery($query);
		$data =  $this->db->loadObjectList();
		echo $this->db->getErrorMsg();
		return $data ;
		 
	}
	
	function parent_list(){
	  
	  $fields  = $this->find( " (type = 1 or type=4 or type=3) and id <> '".$this->id."' ");
	   $list =  array();
	   foreach($fields as $field){
	      $list[$field->id] = $field->name ;
	   }
	   return $list ;
	}
	function hasChild(){
    
	$query = "Select count(*) from #__dtregister_fields where parent_id=".$this->id;
	$this->db->setQuery($query);
	//echo "<br />".$this->db->getErrorMsg();
	return ($this->db->loadResult()>0);
	
  }
  function getchild(){
	    global $mainframe ;
		 $mainframe =& JFactory::getApplication();
	 $condition = "";
         if($mainframe->isAdmin()){
		    
			
			
		 }else{
		    
			$condition = " and hidden = 0 ";
				 
		 }
     $query = "Select * from #__dtregister_fields where parent_id=".$this->id." $condition order by ordering";
	 $this->db->setQuery($query);
	
	 $data =  $this->db->loadObjectList();
	
     return $data ;
  }
  
  function findtree($parent_id=0,&$fields=array()){
     $query = "Select * from #__dtregister_fields where published=1 and parent_id=".$parent_id;
	 $this->db->setQuery($query);
	 $flds = $this->db->loadObjectList();
	  foreach($flds as $data){
	      // debug($data);
		  //$this->dependentReschedule($data['parent']);
		  $fields[$data->id] = $data;
		  $this->id = $data->id ;
		  $childs = $this->getchild();
		  
		  if(count($childs) > 0){
		     foreach($childs as $child){
			   //debug($child);
			   $fields[$child->id] = $child ;
			   $this->findtree($child->id,$fields);
			 }
		     
		  }
	   }
	  
  }
  
  function findall($eventId,$type,$hidden,$parent_id){
     if($type=='B' ||  $type=='M'){
	    $showed_sql  = " in(2,3) ";
		if($type=='B'){
		   if($parent_id > 0){
		      $group_behave_sql = "and ( df.group_behave in (2,3))";
		   }else{
		     $group_behave_sql = "and (fe.group_behave in(2,3) or (fe.showed =-1 and df.group_behave in (2,3)))";
		   }
		}
		if($type == 'M'){
		    if($parent_id > 0){
		      $group_behave_sql = "and ( df.group_behave in (1,3))";
		   }else{
		     $group_behave_sql = "and (fe.group_behave in(1,3) or (fe.showed =-1 and df.group_behave in (1,3)))";
			}
		}
		
	 }else if($type=='I'){
	    $showed_sql  = " in(1,3) ";
		$group_behave_sql = "";
	 }
     if($parent_id == 0){
	   $event_sql =   " fe.event_id=$eventId and " ;
	 }else{
	   $event_sql = " fe.event_id=$eventId and  ";
	 }
	 $hidden_sql = "";
	 if(!$hidden){
	    $hidden_sql = "and df.hidden = 0";
	 }
	 if($parent_id >0){
	   $query = "Select df.* , df.id as key2 From #__dtregister_fields as df  where df.published=1 and ( df.showed $showed_sql) $hidden_sql $group_behave_sql and df.parent_id = $parent_id  order by df.ordering "  ;
	   
	     $query = "Select df.* , df.id as key2 From #__dtregister_fields as df  where df.published=1  $hidden_sql  and df.parent_id = $parent_id  order by df.ordering "  ;
	 }else{
     $query="Select fe.id as key1,   fe.* , df.id as key2 , df.* , if(fe.showed =-1, fe.showed,fe.showed) as showed , if(fe.showed =-1, fe.required,fe.required) as required ,if(fe.showed =-1, fe.group_behave ,fe.group_behave ) as group_behave From #__dtregister_fields as df inner join #__dtregister_field_event as fe on fe.field_id = df.id where $event_sql df.published=1 and (fe.showed $showed_sql or (fe.showed =-1 and df.showed $showed_sql)) $hidden_sql $group_behave_sql and df.parent_id = $parent_id  order by df.ordering ";
	 }
      //$query = "Select * from #__dtregister_fields where parent_id=".$parent_id;
	 $this->db->setQuery($query);
	
	 $data =  $this->db->loadObjectList();
	 //echo "<br />".$this->db->getErrorMsg();
	 // die ;
     return $data ;
  }
  
  function getAllFields($eventId,$type='I',$hidden=false,$parent_id=0,&$fields){
     
	 $flds = $this->findall($eventId,$type,$hidden,$parent_id);
	
	 foreach($flds as $data){
	      // debug($data);
		  //$this->dependentReschedule($data['parent']);
		  $fields[] = $data;
		  if(!isset($data->key2)){
			 $data->key2 = $data->id ;   
		  }
		  $this->id = $data->key2 ;
		  $childs = $this->getchild();
		  
		  if(count($childs) > 0){
		     foreach($childs as $child){
			   //debug($child);
			   $fields[] = $child ;
			   $this->getAllFields($eventId,$type,$hidden,$child->id,$fields);
			 }
		     
		  }
	   }
	 
  }

}

class DT_file{

	var $id ;

	var $path ; 

	function DT_file($id=null){

		$database = &JFactory::getDBO();

		$this->db = &$database;

		if($id!=""){

			$this->id = $id;

		}

	}

	function upload($file,$destfolder=null){

		jimport('joomla.filesystem.file');

		$filename = JFile::makeSafe($file['name']);

		$src = $file['tmp_name'];

        if($destfolder!=""){

		  $destfolder = $destfolder.DS;

		}

		$dest = JPATH_SITE . DS . "images" . DS ."dtregister".DS.$destfolder.$filename;

		if(JFile::exists($dest)){

			$this->re_name($filename,$destfolder);

			$dest =  $this->path;

		}else{

			$this->path = $dest ; 

		}

		return ( JFile::upload($src, $dest) );

	}

	function re_name($filename,$destfolder=null){

	    static $number ; 

		jimport('joomla.filesystem.file');

		$dest = JPATH_SITE . DS . "images" . DS ."dtregister".DS.$destfolder.$filename;

		if(JFile::exists($dest)){

			$ext =  JFile::getExt($filename);

			$name = JFile::stripExt($filename);
            $len = strlen($number);
            if($number>0){
			  $name = substr($name,0,"-".$len);
			}
			$number++ ;

			$name = $name.$number ; 

			$this->re_name($name.".".$ext,$destfolder);

		}else{

		    $this->path = $dest ;

		}

	}

	function remove(){

		jimport('joomla.filesystem.file');

		$sql = "select * from  #__dtregister_files where id=".$this->id;

		$this->db->setQuery($sql);

		$data = $this->db->loadObject();

		JFile::delete($data->path);

		$query = "delete from #__dtregister_files where id=".$this->id;

		$this->db->setQuery($query);

		$this->db->query();

	}

	function save($event_id){

		$query = "insert  #__dtregister_files set path=".$this->db->Quote($this->path)." , event_id = ".$event_id ; 

		$this->db->setQuery($query);

		$this->db->query();

	}

}

class Event{

	var $id;

	function Event($id=null){

		global $database, $gid, $option;

		$database = &JFactory::getDBO();

		$this->db = &$database;

		$this->id =$id;

		if(trim($id)!=""){

			$query = "select article_id from #__dtregister_group_event where eventId = '".$id."' limit 1"	;

			$this->db->setQuery($query);

			$this->article_id = $this->db->loadResult();

			$sql = "SELECT * FROM #__jevents_vevdetail a,#__dtregister_group_event b WHERE a.evdet_id=b.eventId  AND  a.evdet_id=$id";

	        $this->db->setQuery($sql);

	        $data = $this->db->loadObject();
            if($data)
	        foreach($data as $key=>$value){

				$this->$key = $value;

			}

		}

	}
    
	function getTaxAmount($amount=0){
	
	   if($this->tax_enable){
	     $tax_amount =  $amount * $this->tax_amount/100 ;
	   }else{
	      $tax_amount = 0 ;
	   }
	   
	   return $tax_amount ;
	   
	}
	
	function get_cancel_amount($fee_amount,$fee_paid_amount){
	   
	   $this->cancel_fee = cancel_fee($fee_amount);
	   $this->cancel_fee += $this->getTaxAmount($this->cancel_fee);
	   if($this->cancel_refund_status == 0){
	      
			   $this->paying_amount  = $this->cancel_fee;
			   $this->total_fee = $fee_paid_amount + $this->cancel_fee;
			
	   }else{
	     
		     $this->paying_amount =  ($this->cancel_fee - $fee_paid_amount);
			 if($this->paying_amount < 0){
			    $this->paying_amount  = 0 ;
			 }
			 $this->total_fee =   $this->cancel_fee ;
		  
	   }
	   
	}
	
	function get_refund($fee_amount,$fee_paid_amount){
	   $this->cancel_fee = cancel_fee($fee_amount);
	   if($this->cancel_refund_status == 1){
	      if($this->cancel_fee > 0){
		     $this->refund = $fee_paid_amount - $this->cancel_fee ;
		  }else{
		     
			 if($this->cancel_refund_type==1){
			   $this->refund =  $this->cancel_refund_amount;
			 }else if($this->cancel_refund_type==2){
				 $this->refund =  ($fee_paid_amount*$this->cancel_refund_amount)/100 ;
			 }else{
			   return 0;
			 }
		     
		  }
	   }else{
	      $this->refund = 0 ;
	   }
	}
	
	 function getTotalDiscount($amount){
	   global $cb_integrated , $now;
	   $discount = 0 ;
	   if($cb_integrated){
	     $user = &JFactory::getUser();
		 if($user->id>0){
		     if($this->discount_type==3){
			    $discount = ($this->discount_amount*$amount)/100 ;
				$_SESSION['register']['discount']=$discount;
			 }
		 }
	   }
	   
	   if(strtotime($this->bird_discount_date) > strtotime($now->toFormat("%Y-%m-%d")) && $this->bird_discount_type == 3 ){
	      $_SESSION['register']['bird_discount'] = 1 ;
	      $discount  +=  ($this->bird_discount_amount*$amount)/100 ;
	   }
	   
	   return $discount ;
	   
	}
	
	function getValidTask(){
	    
		global $now ;
		$this->registered = $this->getTotalReg() ;
		if((strtotime($this->cut_off_date) < strtotime($now->toFormat('%Y-%m-%d'))) && ($this->cut_off_date!='0000-00-00'))

			$task="cut_off_date";

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

			$task="full_event_page";

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

      		$task="full_event_page_msg";
		else

      		$task="reg_event";
			
			return  $task ;
		
	}
	
	function is_registerable(){
	   global $Itemid ;
	   $task = $this->getValidTask() ;
	   $this->redirection = "index.php?option=com_dtregister&Itemid=".$Itemid."&eventId=".$this->id."&task=".$task;
	   return ( $task == 'reg_event') ;
	
	}
	
	function getTotalReg(){
	    
		$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=".$this->id." and a.cancel <> 1 

				  GROUP BY a.eventId

				";

			$this->db->setQuery($sql);
            $total =  $this->db->loadResult();
			if(!$total){
			   $total = 0 ; 
			}
			return $total ;

	}
	
	function get_field($field){

		$query = "select ".$field." from #__dtregister_group_event where eventId = ".$this->id . " limit 1"	;

		$this->db->setQuery($query);

		$this->$field = $this->db->loadResult();

		return $this->$field ; 

	}
    
    function get_total_fee($memtot=1,$cb_user,$date=null){
	   
	   $slab = $this->get_slab($memtot,$date);
	   
	   if($memtot == 1){
	     $amountperRate = $slab->registerAmountIndividual ;
	   }else{
	      $amountperRate = $slab->regGroupPerRate ;
	       
	   }
	   $discount = 0 ;
	   $latefee = 0 ;
	   if($cb_user > 0){
	      if($slab->discount_type==1){

			 $amountCharged = ($amountperRate-$slab->discount_amount)* $memtot;

			 $discount = $slab->discount_amount * $memtot; 
             
		  } elseif ($slab->discount_type==2){
            
		 	$amountCharged = $amountperRate*(100-$slab->discount_amount) * $memtot/100;

			$discount = (($amountperRate*$slab->discount_amount)/100) * $memtot;
        
		  } else {
            
			$amountCharged = $amountperRate * $memtot;

		  }
	   }else{
	       
	       $amountCharged = $amountperRate * $memtot;
           			
	   }
	   if($slab->late=='y'){
  
	        $latefee = $slab->latefee*$memtot;
            $amountCharged = $latefee + $amountCharged;

		}
		$this->member_discount = $discount ;
		$this->latefee = $latefee ;
		
		return $amountCharged ;
	   
	}
	
	function get_fee($memtot=1,$cb_user=0){
        
		global $now ;
		$database = &JFactory::getDBO();
		
		if($memtot == 1){

			$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=".$this->id." AND memberTotal=".$memtot;

			$amountCharged = 0;

            $latefee =0;
           $this->db->setQuery($query);
			$res = $this->db->loadObjectList();
		
			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);
		    
		             }

					$amountCharged = $r->registerAmountIndividual;

					if($r->late=='y'){

						//$latefee += $res['latefee'];

						$late_fee_rate = $r->latefee;

						$latefee = $late_fee_rate;

					}

				}

			 	$discount_total=0;

			 	$database->setQuery($query);

 			 	$discount_type = $r->discount_type;

			 	$discount_amount = $r->discount_amount;

			 	$late_fee_rate = $r->latefee;

			 	$group_per_rate = $r->regGroupPerRate;

			 	$discount_per_rate = $r->discount_amount;

				$totalCharged = $amountCharged + $latefee;

			 	if($cb_user > 0){

			 	//Apply discount here

					$discount_total=0;

					if($discount_type==1){

					//Amount

						$discount_total = $discount_amount;

						$totalCharged=$totalCharged-$discount_amount;

					} elseif ($discount_type==2) {

					//Percent

						$discount_total = $totalCharged * ($discount_amount/100);

						$totalCharged=$totalCharged*(100-$discount_amount)/100;

					}

				//End of discount here

				$this->member_discount=$discount_total;

				}

			}

		}else{

			 $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=".$this->id." ORDER BY memberTotal ASC";

			 $this->db->setQuery($query);

			 $res = $this->db->loadObjectList();

			 $amountCharged = 0;

			 $latefee =0;

			 $discount=0;

			 foreach($res as $r){

			    // memberTotal is 'Number of members' on the admin side

			    if( (int)$memtot >= $r->memberTotal){
                    
					 if($r->bird=='y'){
		 
		               $r->registerAmountIndividual = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->registerAmountIndividual);
		    
		             }
					 
					 if($r->bird=='y'){
		 
		               $r->regGroupPerRate = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->regGroupPerRate);
		    
		             }
					$discount_type = $r->discount_type;

			    	$discount_amount = $r->discount_amount;

			    	$late_fee_rate = $r->latefee;

			    	$group_per_rate = $r->regGroupPerRate;

			    	#$discount_per_rate = $r->discount_amount;

			    	$discount=0;

				    $this->member_discount = 0;

				    $group_per_rate = $r->regGroupPerRate;

					if($cb_user>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;

						$this->member_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;

				}

			}

		}

		return $totalCharged ;

	}

	function getdiscount_codes(){

		$query ="select * from  #__dtregister_events_codes where event_id=".$this->id;

		$this->db->setQuery($query);

		$data =  $this->db->loadObjectList();

		$codes = array();

		if($data){

			foreach($data as $value){

				$codes[] = $value->discount_code_id;

			}

		}

		return $codes;

	}

	function assign_discountcodes($dt_codes=array()){

		$query = "delete from #__dtregister_events_codes where event_id =".$this->id;

		$this->db->setQuery($query);

		$this->db->query();

		if(is_array($dt_codes)){

			foreach($dt_codes as $value){

				$query = "insert #__dtregister_events_codes set discount_code_id=".$value.",event_id =".$this->id;

				$this->db->setQuery($query);

				$this->db->query();

			}

		}

	}

	function get_article(){

		$query = "select * from #__content where id=".$this->article_id;

		$this->db->setQuery($query);

		return $this->db->loadObject();

	}

    function get_article_Item($article){
    
		if($this->detail_itemid !="" && $this->detail_itemid !='0'){
		   return $this->detail_itemid ;
		}
		
		$query = "select * from #__menu where link like '%option=com_content%' and link like '%view=article%' and  link like '%id=".$this->article_id."%' ";

		$this->db->setQuery($query);
      
		$this->db->query();

		if($this->db->getNumRows()>0){

			$menu =  $this->db->loadObject();

			return $menu->id ; 

		}else{

			$query = "select * from #__menu where link like '%option=com_content%' and link like '%view=category%' and  link like '%id=".$article->catid."%' ";

			$this->db->setQuery($query);

			$this->db->query();

			if($this->db->getNumRows()>0){

				$menu =  $this->db->loadObject();

				return $menu->id ; 

			}else{

				$query = "select * from #__menu where link like '%option=com_content%' and link like '%view=section%' and  link like '%id=".$article->sectionid."%' ";

				$this->db->setQuery($query);

				$this->db->query();

				if($this->db->getNumRows()>0){

					$menu =  $this->db->loadObject();

					return $menu->id ; 

				}else{

					return 0 ;

				}

			}

		}

	}

	function save_files($files){

		if(!isset($files['name'][1])){

		}else{

			$file = array();

			for($i=1;$i<count($files['name']);$i++){

				$file['name'] =  $files['name'][$i];

				$file['type'] =  $files['type'][$i];

				$file['tmp_name'] =  $files['tmp_name'][$i];

				$file['size'] =  $files['size'][$i];

				$file['error'] =  $files['error'][$i];

				$dt_file = new DT_file();

				if($dt_file->upload($file)){

					$dt_file->save($this->id);

				}

				unset($dt_file);

			}

		}

	}
     function is_passed(){
	   
	   global $now ;
	   $sql = "Select dtstart from #__jevents_vevdetail as a inner join #__dtregister_group_event as b on a.evdet_id = b.eventId where  b.eventId= ".$this->id;
	   // a.dtstart < '".$now->toUnix(true)."' and
	   $this->db->setQuery($sql);
	   $startdate = $this->db->loadResult() ;
	   
	   if($startdate == ""){
		   return true ;
	   }
	  
	  return ($startdate < $now->toUnix(true));
	   
	}
	function cutoff_passed(){
	   
	   global $now ;
	   $sql = "Select count(*) from #__jevents_vevdetail as a inner join #__dtregister_group_event  as b on a.evdet_id = b.eventId where b.cut_off_date < '".$now->toFormat("%Y-%m-%d")."' and  b.cut_off_date <> '0000-00-00' and b.eventId= ".$this->id;
	   
	   $this->db->setQuery($sql);

	  return ($this->db->loadResult() > 0);
	   
	}
	 function read(){
	  $sql = "select * from #__dtregister_fields where id=".$this->id." order by ordering" ;
	   $this->db->setQuery($sql);

	   $data = $this->db->loadObject(); 
	   foreach($data as $key=>$value){
	     $this->$key = $value;
	   }
	   
	}
	function field_html($type='I',$user = null,$showHidden=false,$form='frmcart',$overlimitdisable=true){
	  
	   $this->javavalidation = "";
	   if($type=="I"){
	      $fields = $this->get_individual_custom_field($showHidden);
	   }elseif($type=="B"){
	      $fields = $this->get_billing_custom_field($showHidden);
	   }else{
	      $fields = $this->get_group_custom_field($showHidden);
	   }
	   $html = ""; 
	  JHTML::_('behavior.tooltip','.DtTip'); 
	  
	   foreach($fields as $field){
	     
	      $cfield = new Custom_field($field->id);
		  $cfield->read();
		  if($cfield->parent_id){
		     continue ;
		  }
		   if($showHidden && $cfield->type==6){
		     continue ;   
		   }
		  $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";
		  }
		  $field->label = stripslashes($field->label).":";
		  if($field->required){
		    $field->label = $field->label." <span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span> ";
		  }
		  
		  $tpl = file_get_contents($file);
		  $constants = array('[label]','[value]','[description]');
		  $description =  (trim($cfield->description)!="")?DTHTML::tooltip($cfield->description, '', 'tooltip.png', '', ''):'';
		  $replace  = array($field->label,$cfield->formhtml($user,$this,$form,$overlimitdisable),$description);
		  if($field->required){
		     $this->javavalidation .= $cfield->javascript ;
			 
			 
		  }
		  $this->javavalidation .= $cfield->addChildValidation($user,$this,$form,$overlimitdisable) ;
		  $this->javavalidation .= $cfield->javascript_valid_data ;
		  
	      $html .= str_replace($constants,$replace,$tpl);
	   }
	    
	   return $html ;
	}
	function field_view($type,$user = null,$showHidden=false){
	   if($type=="I"){
	      $fields = $this->get_individual_custom_field($showHidden);
	   }elseif($type=="B"){
	      $fields = $this->get_billing_custom_field($showHidden);
	   }else{
	      $fields = $this->get_group_custom_field($showHidden);
	   }
	   $html = ""; 
	  
	   foreach($fields as $field){
	      $cfield = new Custom_field($field->id);
		  $file = "components/com_dtregister/view/field/field".$field->type.".php";
		  if (!file_exists($file)) {
		     $file = "components/com_dtregister/view/field/field.php";
		  }
		 
		   $tpl = file_get_contents($file);
		  
		  $constants = array('[label]','[value]','[description]');
		  $field_data = $cfield->html($user,$this);
		  $field->label = stripslashes($field->label)." : ";
		  if($field_data!=""){
		     $replace  = array($field->label,nl2br($cfield->html($user,$this)),'');
	         $html .= str_replace($constants,$replace,$tpl);
		  }
		  
	   }
	   
	   return $html ;
	}
	function formhtml($obj=null,$event,$form="frmcart",$overlimitdisable=true){
	 
	  $this->read();
	  $new_line=$this->new_line;
	  $this->javascript = "";
	  $this->selected = stripslashes($this->selected);
	  
	  switch($this->type){
	     case 0:
             //Text box
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
			 $maxlength = ($this->maxlength !=0 && $this->maxlength=="")?"maxlength='".$this->maxlength."'":'';
			 $this->javascript = "if (document.{$form}.{$this->name}.value == ''){
                                       alert('{$this->label} is required');
                                       document.{$form}.{$this->name}.focus();
                                       return;
                                    }";
									$maxlength = ($this->maxlength !=0 && $this->maxlength=="")?"maxlength='".$this->maxlength."'":'';
             return "<input type='text' class='inputbox' ".$maxlength." size='$this->field_size' name='$this->name' value='$value' />" ;
         break;
		 case 1:
                //Drop down
			  $this->optionlimit = $this->get_option_limit($event->id);
              $this->optionused = $this->option_usage($event->id,$obj);
			  $fieldSize=$this->field_size;
              $dropDownDatas=explode("|",$this->values);
              $options=array();
			  $value = isset($obj->{$this->name})?$obj->{$this->name}:$this->selected;
              for($i=0,$n=count($dropDownDatas);$i<$n;$i++){
                 if(!is_array($this->optionlimit) ||(isset($this->optionlimit[$i]) && $this->optionlimit[$i]==0 ) ){
                      
					 $options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]));
                 }else{
                      if($this->optionlimit[$i] > $this->optionused[$i] ){
                          $options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]));
					  }

			     }
                 	//$options[]=JHTML::_('select.option',trim($dropDownDatas[$i]),trim($dropDownDatas[$i]));
               }
			    $this->javascript = "if (document.{$form}.{$this->name}.value == ''){
                                       alert('{$this->label} is required');
                                       document.{$form}.{$this->name}.focus();
                                       return;
                                    }";
              return JHTML::_('select.genericlist', $options,$this->name,"style='width:".$fieldSize."px'","value","text",$value) ;
    	 break;
		 case 2:
               //Text area
			    $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
				$this->javascript = "if (document.{$form}.{$this->name}.value == ''){
                                       alert('{$this->label} is required');
                                       document.{$form}.{$this->name}.focus();
                                       return;
                                    }";
               return "<textarea name='$this->name' rows=$this->rows cols=$this->cols>$value</textarea>" ;
         break;
		 case 3:
              //Checkbox
			 $this->optionlimit = $this->get_option_limit($event->id);
             $this->optionused = $this->option_usage($event->id,$obj);
             $dropDownDatas=explode("|",$this->values);
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:$this->selected;
             $arrValues=explode("|",$value);
            //Trim the space
             for($i=0,$n=count($arrValues);$i<$n;$i++){
                 $arrValues[$i]=trim($arrValues[$i]);
             }
             //Get custom data
             $outPut="";
             for($i=0,$n=count($dropDownDatas);$i<$n;$i++){
                  if(isset($this->optionlimit[$i]) && $this->optionlimit[$i]!=0 && $this->optionlimit[$i] <= $this->optionused[$i]){
                       continue ;
                  }
                  $data=trim($dropDownDatas[$i]);
                  if(in_array($data,$arrValues)){
                     if($new_line)
                         $outPut.="<input name='$this->name[]' value='".htmlentities($data, ENT_QUOTES)."' checked type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                     else
                          $outPut.="<input name='$this->name[]' value='".htmlentities($data, ENT_QUOTES)."' checked type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                   }else{
                        if($new_line)
                           $outPut.="<input name='$this->name[]' value='".htmlentities($data, ENT_QUOTES)."' type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                        else
                           $outPut.="<input name='$this->name[]' value='".htmlentities($data, ENT_QUOTES)."' type='checkbox' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                    }
             }
			 $values=explode("|",$this->values);
             $totalValues=count($values);
			
			$this->javascript ="var success=false;
                                   for(var i=0;i<$totalValues;i++){
                                      var ckb=document.getElementById('{$this->name}'+i);
                                      if(ckb.checked==true){
                                         success=true;
                                         break;
                                      }
                                   }
                                   if(!success){
                                      alert('{$this->label} is required');
                                      return;
                                   }";
			 
              return $outPut;
         break;
		 case 4:
             //Radio list
			 $this->optionlimit = $this->get_option_limit($event->id);
             $this->optionused = $this->option_usage($event->id,$obj);
             $dropDownDatas=explode("|",$this->values);
			 
			 $value = isset($obj->{$this->name})?$obj->{$this->name}:$this->selected;
             $arrValues=explode("|",$value);
			 //Trim the space
             for($i=0,$n=count($arrValues);$i<$n;$i++){
                  $arrValues[$i]=trim($arrValues[$i]);
             }
             //Get custom data
             $outPut="";
             for($i=0,$n=count($dropDownDatas);$i<$n;$i++){
                   
                 if(isset($this->optionlimit[$i]) && $this->optionlimit[$i]!=0 && $this->optionlimit[$i] <= $this->optionused[$i]){
                     continue ;
                 }
                 $data=trim($dropDownDatas[$i]);
				 
                 if(in_array($data,$arrValues)){
                      if($new_line) 
                         $outPut.="<input name='$this->name' value='$data' type='radio' checked id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                      else
                         $outPut.="<input name='$this->name' value='$data' type='radio' checked id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                 }else{
                     if($new_line)
                        $outPut.="<input name='$this->name' value='$data' type='radio' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;<br />";
                     else
                        $outPut.="<input name='$this->name' value='$data' type='radio' id='".$this->name.$i."' />&nbsp;&nbsp;$data&nbsp;&nbsp;";
                 }
             }
			 $values=explode("|",$this->values);
             $totalValues=count($values);
			 $this->javascript ="var success=false;
                                   for(var i=0;i<$totalValues;i++){
                                      var rd=document.getElementById('{$this->name}'+i);
                                      if(rd.checked==true){
                                         success=true;
                                         break;
                                      }
                                   }
                                   if(!success){
                                      alert('{$this->label} is required');
                                      return;
                                   }";
			 
             return $outPut;
          break;
		 case 5:
              //Date custom fields
			$value = isset($obj->{$this->name})?$obj->{$this->name}:'';
            $format = ($this->date_format !='')?$this->date_format:'%Y-%m-%d';
            $outPut = JHTML::_("calendar",$value,$this->name,$this->name,$format,"class=' text_area datetype '");
			$this->javascript = "if (document.{$form}.{$this->name}.value == ''){
                                       alert('{$this->label} is required');
                                       document.{$form}.{$this->name}.focus();
                                       return;
                                    }";
			
			return $outPut;
          break;
		    case 7:
			      $name =  $this->name ;
			      $value = isset($obj->{$this->name})?$obj->{$this->name}:'';
				  $listCustoms[$name] = "<input class='inputbox' name='file_$name' value='' type='file' /> <button filename='$name' class='upload' filetype='".$this->filetypes."' filesize='".$this->filesize."' >".JText::_( 'DT_UPLOAD' )."</button><input type='hidden' name='$name' id='$name' value='' />&nbsp;".$value;
				    $this->javascript = "if (document.frmcart.{$this->name}.value == ''){
                                       alert('{$this->label} is required');
                                       document.frmcart.{$this->name}.focus();
                                       return;
                                    }";
									
				  break ;
		  case 6:

             return stripslashes($this->textual);
          }
   }
	function html($obj=null){
	  $this->read();
	  if($this->type!=6){
	    return $obj->{$this->name} ;
	  }
	  return "";
	
	}
	
    function get_location(){
	   
	     $loc = new DTlocation($this->db);
         if($this->location_id==""){
		   return false ;
		 }
		 $loc->load($this->location_id); 
		 
		 return $loc ;
	   
	}

	function get_files(){

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

		  return array();

		}

		$query = "select * from #__dtregister_files where event_id=".$this->id;

		$this->db->setQuery($query);

		return $this->db->loadObjectList();

	}

	function assign_article($article_id){

		$query = "update #__dtregister_group_event set article_id=".$article_id." where eventId =".$this->id;

		$this->db->setQuery($query);

		$this->db->query();

	}

	function save_field($field,$value){

		$query = "update #__dtregister_group_event set ".$field."=".$this->db->Quote($value)." where eventId =".$this->id;

		$this->db->setQuery($query);

        //$this->db->getQuery();
		
		//$this->db->getErrorMsg();

		$this->db->query();

	}
    function get_group_custom_field($showHidden=false){
         
		 global $now ;
		 $hidden_sql =  ($showHidden)?'':' and df.hidden=0 ';
		 $sql="Select fe.id as key1,   fe.* , df.id as key2 , df.*, if(fe.showed =-1, fe.showed,fe.showed) as showed , if(fe.showed =-1, fe.required,fe.required) as required ,if(fe.showed =-1, fe.group_behave ,fe.group_behave ) as group_behave From #__dtregister_fields as df  inner join #__dtregister_field_event as fe on df.id = fe.field_id where fe.event_id=".$this->id." and (fe.showed in(2,3) or (fe.showed =-1 and df.showed in(2,3))) and df.published=1  ".$hidden_sql." and (fe.group_behave in(1,3) or (fe.showed =-1 and df.group_behave in(1,3)) ) order by df.ordering ";

		$this->db->setQuery($sql);
        $this->db->getQuery();
		 $rowCustoms=$this->db->loadObjectList();
         
		return $rowCustoms;

	}
	
	function get_fee2($memtot=1,$cb_user=0){
        
		global $now ;
		if($memtot == 1){

			$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=".$this->id." AND memberTotal=".$memtot;

			$amountCharged = 0;

            $latefee =0;

			$res = $this->db->loadObjectList();

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

		             }

					$amountCharged = $r->registerAmountIndividual;

                    if($res['bird']=='y'){

					}

					if($res['late']=='y'){

						//$latefee += $res['latefee'];

						$late_fee_rate = $r->latefee;

						$latefee = $late_fee_rate;

					}

				}

			 	$discount_total=0;

			 	$this->db->setQuery($query);

 			 	$discount_type = $r->discount_type;

			 	$discount_amount = $r->discount_amount;

			 	$late_fee_rate = $r->latefee;

			 	$group_per_rate = $r->regGroupPerRate;

			 	$discount_per_rate = $r->discount_amount;

				$totalCharged = $amountCharged + $latefee;

			 	if($cb_user > 0){

			 	//Apply discount here

					$discount_total=0;

					if($discount_type==1){

					//Amount

						$discount_total = $discount_amount;

						$totalCharged=$totalCharged-$discount_amount;

					} elseif ($discount_type==2) {

					//Percent

						$discount_total = $totalCharged * ($discount_amount/100);

						$totalCharged=$totalCharged*(100-$discount_amount)/100;

					}

				//End of discount here

				$this->member_discount=$discount_total;

				}

			}

		}else{

			 $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=".$this->id." ORDER BY memberTotal ASC";

			 $this->db->setQuery($query);

			 $res = $this->db->loadObjectList();

			 $amountCharged = 0;

			 $latefee =0;

			 $discount=0;

			 foreach($res as $r){

			    // memberTotal is 'Number of members' on the admin side

			    if( (int)$memtot >= $r->memberTotal){

					$discount_type = $r->discount_type;

			    	$discount_amount = $r->discount_amount;

			    	$late_fee_rate = $r->latefee;

                   if($r->bird=='y'){

		               $r->regGroupPerRate = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->regGroupPerRate);

		            }

			    	$group_per_rate = $r->regGroupPerRate;

			    	#$discount_per_rate = $r->discount_amount;

			    	$discount=0;

				    $this->member_discount = 0;

				    $group_per_rate = $r->regGroupPerRate;

					if($cb_user>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;

						$this->member_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;

				}

			}

		}

		return $totalCharged ;

	}

	function get_slab($membercount){
         global $now ;
		 $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=".$this->id." and memberTotal <= ".$membercount." ORDER BY memberTotal desc limit 1";
      
		 $this->db->setQuery($query);
 
		return $this->db->loadObject();

	}

	function get_custom_fields_fee($data=array(),$type='I'){
        
		
		
		$sql="Select fe.id as key1,   fe.* , df.id as key2 , df.* From #__dtregister_fields as df inner join #__dtregister_field_event  as fe on df.id = fe.field_id where fe.event_id=".$this->id." and (fe.showed > 0 or (fe.showed = -1 and df.showed > 0)) and df.published=1 and df.fee_field = 1 order by  df.fee_type ";
         
		 if(!is_array($data) || !(count($data)>0)){
		     $data=Jrequest::get('post');
		 }
         $memtol = isset($_SESSION['register']['memtot'])?$_SESSION['register']['memtot']:1 ;
		
        $slab = $this->get_slab($memtol);

		if($memtol == 1){

		  $amount = $slab->registerAmountIndividual;

		}else{

		   $amount = $slab->regGroupPerRate;

		}
        if($slab->bird=='y'){

		  $amount = bird_discount_calc($slab->bird_discount_type,$slab->bird_discount_amount,$amount );

		}
		$user = &JFactory::getUser();
       
       $memtol = isset($_SESSION['register']['memtot'])?$_SESSION['register']['memtot']:1 ;
		$total_fee = $this->get_fee($memtol,$user->id);

		if($memtol > 1 && isset($_SESSION['register']['groupUser'])){

		  $groupFee = 0 ;

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

			$groupFee += $_SESSION['register']['groupUser'][$key]['customFee'];

		  }

		  $total_fee += $groupFee ; 

		}

		$this->db->setQuery($sql);

		$rowCustoms=$this->db->loadObjectList();
        
		$fld = new Custom_field();
		
        $fields =  array();
	    
		
		
		$fld->getAllFields($this->id,$type,false,0,$fields) ;
			
			$rowCustoms = $fields ;
		
		$fee = 0;

       // echo "<pre>";

		// print_R($rowCustoms);

		//echo "</pre>";

		foreach($rowCustoms as $key=>$rowCustom){
           
		    if($type=='M' && $rowCustom->fee_type==3){
			   	$rowCustom->fee_type = 2 ;
		    }
			
			if(isset($data[$rowCustom->name])){

				switch($rowCustom->type){
                    case 2:
					    
						$fee += getTextareaFee(strlen(stripslashes($data[$rowCustom->name])),$rowCustom->textareafee);
						
						
						
					break ;
					case 4:

								$custom_values = explode("|",str_replace(" ","",$rowCustom->values));

						$custom_fee   = explode("|",str_replace(" ","",$rowCustom->fees));

						$custom_values = array_slice($custom_values,0,count($custom_fee));

						$custom_fee = array_combine($custom_values,$custom_fee);

                         $temp = array();

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

						   $temp[trim($key)] = $value ;

						}

						$custom_fee = $temp ;

						if(is_array($data[$rowCustom->name])){

							foreach($data[$rowCustom->name] as $postevalue){

							  $postevalue =  str_replace(" ","", $postevalue);
                               
                               if($rowCustom->fee_type ==3){

						           $fee += amount_percentage(2,($total_fee+$fee),$custom_fee[str_replace(" ","",$data[$rowCustom->name])]);

						       }elseif($rowCustom->fee_type ==2){

								   $fee += amount_percentage(2,$amount,$custom_fee[$postevalue]);

								}else{

								   $fee += $custom_fee[$postevalue];

								}

							}

						}else{

                              if($rowCustom->fee_type ==3){
                                   $fee += amount_percentage(2,($total_fee+$fee),$custom_fee[str_replace(" ","",$data[$rowCustom->name])]);
                               
						       }elseif($rowCustom->fee_type ==2){

								   $fee += amount_percentage(2,$amount,$custom_fee[str_replace(" ","",$data[$rowCustom->name])]);

								}else{

								   $fee += $custom_fee[str_replace(" ","",$data[$rowCustom->name])];

								}

						}

					break;

					case 3:

					   $custom_values = explode("|",str_replace(" ","",$rowCustom->values));

					   $custom_fee   = explode("|",str_replace(" ","",$rowCustom->fees));

						$custom_values = array_slice($custom_values,0,count($custom_fee));

						$custom_fee = array_combine($custom_values,$custom_fee);
                        
					     $temp = array();

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

						   $temp[trim($key)] = $value ;

						}

						$custom_fee = $temp ;

                        if(!is_array($data[$rowCustom->name])){
						    if(strrchr($data[$rowCustom->name],'|')){
							    $data[$rowCustom->name] = explode("|",$data[$rowCustom->name]);
							}else{
							   $data[$rowCustom->name] = explode(",",str_replace(',','[tokencomma]',$data[$rowCustom->name]));
							   $data[$rowCustom->name] = str_replace('[tokencomma]',',',$data[$rowCustom->name]);
							}
						    
						}
						
						foreach($data[$rowCustom->name] as $postevalue){

						     if($rowCustom->fee_type ==3){

						           $fee += amount_percentage(2,($total_fee+$fee),$custom_fee[str_replace(" ","",$postevalue)]);

						    }elseif($rowCustom->fee_type ==2){

								 $fee += amount_percentage(2,$amount,$custom_fee[str_replace(" ","",$postevalue)]);

							}else{

								 $fee += $custom_fee[str_replace(" ","",$postevalue)];

							}

						}

					 break;

					default:

					   $custom_values = explode("|",str_replace(" ","",$rowCustom->values));

						$custom_fee   = explode("|",str_replace(" ","",$rowCustom->fees));

						$custom_values = array_slice($custom_values,0,count($custom_fee));

						$custom_fee = array_combine($custom_values,$custom_fee);

						 $temp = array();

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

						   $temp[trim($key)] = $value ;

						}

						$custom_fee = $temp ;

					    if($rowCustom->fee_type ==3){

						   $fee += amount_percentage(2,($total_fee+$fee),$custom_fee[str_replace(" ","",$data[$rowCustom->name])]);

						}elseif($rowCustom->fee_type ==2){

						   $fee += amount_percentage(2,$amount,$custom_fee[str_replace(" ","",$data[$rowCustom->name])]);

						}else{

						   $fee += $custom_fee[str_replace(" ","",$data[$rowCustom->name])];

						}

				}

				/*$custom_values = explode("|",$rowCustom->values);

				$custom_fee   = explode("|",$rowCustom->fees);

				if(count($custom_values)==count($custom_fee)){

				}else{

					$custom_values = array_slice($custom_values , 0,count($custom_fee));

				}

				$custom_fee = array_combine($custom_values,$custom_fee);

				if(is_array($data[$rowCustom->name])){

					foreach($data[$rowCustom->name] as $postevalue){

						$fee += $custom_fee[$postevalue];

					}

				}else{

					$fee += $custom_fee[$data[$rowCustom->name]];

				}*/

			}

		}

		$this->custom_fee = $fee;

		return $fee ; 

	}

	function get_billing_custom_field($showHidden=false){
        
         
	 $fld = new Custom_field();
			$fields=array() ;
			
		   
            $fld->getAllFields($this->id,'B',$showHidden,0,$fields) ;
			
			$rowCustoms = $fields ;
			foreach($rowCustoms  as &$field){
			   $field->field_id = $field->id ;
			}
		return $rowCustoms;

	}

	function get_fields(){

		 $sql = "Select df.id , df.name,df.label From #__dtregister_field_event as fe inner join #__dtregister_fields as df on fe.field_id=df.id where fe.event_id=".$this->id." and (fe.showed<>0 or (fe.showed = - 2 and df.showed <> 1))";

		$this->db->setQuery($sql);

		return $this->db->loadObjectList();

	}

   function getAllFields(){

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

		  return array();

		}

		 $sql="SELECT  e.id as key1 , f.id as key2 , f.* ,   e.* FROM #__dtregister_fields f, #__dtregister_field_event e WHERE e.field_id=f.id AND e.event_id=".$this->id." ";

		$this->db->setQuery($sql);

		 $fields = $this->db->loadObjectList();

		 $temp = array();

		 foreach($fields as $key => $field){

		    $temp[$field->field_id] = $field ;

		 }

		return $temp ;

	}

	function getAllslabs(){

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

		  return array();

		}   

	    $sql = "select * from #__dtregister_group_event WHERE eventid=".$this->id." and memberTotal > 1 ORDER BY memberTotal ";

		$this->db->setQuery($sql);

		 return  $this->db->loadObjectList();

	}

	function get_custom_fields_attendee_list(){

        $flds =  new Custom_field();
		$fields = array();
		$flds->getAllFields($this->id,'I',false,0,$fields);
		$attendee_field =  array() ;
		foreach($fields  as $field){
		   if($field->attendee_list){
		     $attendee_field[$field->id] = $field ;
			}
		}
		$fields = array();
		$flds->getAllFields($this->id,'B',false,0,$fields);
		foreach($fields  as $field){
		   if($field->attendee_list && !isset($attendee_field[$field->id])){
		     $attendee_field[$field->id] = $field ;
			}
		}
		$fields = array();
		$flds->getAllFields($this->id,'M',false,0,$fields);
		foreach($fields  as $field){
		   if($field->attendee_list && !isset($attendee_field[$field->id])){
		     $attendee_field[$field->id] = $field;
			}
		}
		return $attendee_field;

	}

	function get_jev_detail(){

		 $sql="SELECT * FROM #__jevents_vevdetail WHERE evdet_id=".$this->id." ";

		$this->db->setQuery($sql);

		return $this->db->loadObject();

	}

	function findall(){

	   $sql = "select * from #__dtregister_group_event as ge inner join #__jevents_vevdetail as je on je.evdet_id = ge.eventId group by ge.eventId ";

	   $this->db->setQuery($sql);

	   return $this->db->loadObjectList();

	}
    
	function save_prerequisite($prerequisite=array()){
	   
	   $sql = "delete  from #__dtregister_prerequisite where event_id = ".$this->id;

       $this->db->setQuery($sql);
	   $this->db->query();
	   if(is_array($prerequisite))
	   foreach($prerequisite as $event){
	      
		   $sql = "insert into #__dtregister_prerequisite set prerequisite_id=$event , event_id=".$this->id;
		   $this->db->setQuery($sql);
	       $this->db->query();
	   }
	   
	}
	
	function save_prerequisite_category($prerequisite=array()){
	   
	   $sql = "delete  from #__dtregister_prerequisite_category where event_id = ".$this->id;

       $this->db->setQuery($sql);
	   $this->db->query();
	   if(is_array($prerequisite))
	   foreach($prerequisite as $category){
	      
		   $sql = "insert into #__dtregister_prerequisite_category set prerequisite_id=$category , event_id=".$this->id;
		   $this->db->setQuery($sql);
	       $this->db->query();
	   }
	   
	}
	
    function get_prerequisite(){
	   
	   // $this->id." 
	   
	   $sql = "select * from #__dtregister_prerequisite where event_id = ".$this->id;

	   $this->db->setQuery($sql);

	   return $this->db->loadObjectList();
	   
	}
	
	function get_prerequisite_category(){
	   
	   // $this->id." 
	   
	   $sql = "select * from #__dtregister_prerequisite_category where event_id = ".$this->id;

	   $this->db->setQuery($sql);

	   return $this->db->loadObjectList();
	   
	}

	function get_registrants(){

		$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=".$this->id." and a.cancel <> 1

				  GROUP BY a.eventId

				";

	    $this->db->setQuery($sql);

		return $this->db->loadResult();

	}

	function get_individual_rate(){
          
		  global $now ;
	    	$sql="SELECT a.registerAmountIndividual 

, if('".$now->toFormat("%Y-%m-%d")."' < bird_discount_date and bird_discount_type<>0 and bird_discount_type <> 3,'y','n') as bird , 

                  a.bird_discount_amount , a.bird_discount_type

				  FROM #__dtregister_group_event AS a

				    WHERE a.eventId=".$this->id." 

				    order by a.memberTotal limit 1

				";

	   $this->db->setQuery($sql);

       $this->db->getErrorMsg();

		$r = $this->db->loadObject();

		if($r->bird=='y'){

		             $r->registerAmountIndividual = bird_discount_calc($r->bird_discount_type,$r->bird_discount_amount,$r->registerAmountIndividual);

		         }

				 return $r->registerAmountIndividual ;

	} 

	function save_config($data){

	   $sql =  "delete from #__dtregister_event_config where eventId=".$this->id;

	   $this->db->setQuery($sql);

       $this->db->query();

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

		  if(is_array($value)){

		     $value = implode(",",$value);

		  }

		$field=$this->db->Quote($key);

		$value=$this->db->Quote($value);

		$sql="Insert Into #__dtregister_event_config(eventId,`key`,value) Values(".$this->id.",$field,$value)";

		$this->db->setQuery($sql);

        $this->db->getQuery($sql);

		$this->db->query();

	   }

	}

	function over_ride_global($over_ride=false){

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

		  return 0;

		}

		if($over_ride==true){

		 $prev = isset($this->payment_option)?$this->payment_option:'' ;

		 $this->payment_option = 2 ; 

		}

		 if($this->payment_option ==1){
          
		  return 0;

		}

	    $sql = "Select * from #__dtregister_event_config where eventId=".$this->id;

		$this->db->setQuery($sql);

		$data = $this->db->loadObjectList();

		if($data)

		foreach($data as $value){

		  $name = $value->key ;

		  $str = " global \$".$name.";";

		  eval($str);

		  $$name = $value->value ;
		  
		  $this->$name = $value->value ;
		  
		   $$name ;

		}
       
		 if($over_ride==true){

		   $this->payment_option = $prev ; 

		}

	}
	
	function over_ride(){
	   
	   $vars = array("pay_later_thk_msg");
	   $sql = "Select * from #__dtregister_event_config where eventId=".$this->id." and `key` in('".explode("', '",$vars)."')";
	   $this->db->setQuery($sql);

	   $data = $this->db->loadObjectList();
       foreach($data as $value){

		  $name = $value->key ;

		  $str = " global \$".$name.";";

		  eval($str);

		  $$name = $value->value ;
		  
		   $$name ;

		}
	   
	}
	
	function resume_global(){
		 global $DT_CONFIG ;
	     $sql = "Select * from #__dtregister_event_config where eventId=".$this->id;

		$this->db->setQuery($sql);

		$data = $this->db->loadObjectList();

		if($data)

		foreach($data as $value){

		  $name = $value->key ;

		  $str = " global \$".$name.";";

		  eval($str);
         /*$sql="Select id , config_key,config_value From #__dtregister_config where config_key='$name'";
		  
	      $this->db->setQuery($sql);
          $rowConfigs=$this->db->loadObjectList();*/
		  
		 // $rowConfigs = $rowConfigs[0]; //&& isset($DT_CONFIG[$name])
		  if(isset($DT_CONFIG[$name]) ){
		    $rowConfigs = $DT_CONFIG[$name] ;
		     $$name = $rowConfigs->config_value ;
		  }
		  
		  unset($$name);
		  
		}
		
	}
	
    function get_individual_custom_field($showHidden=false){

    $hidden_sql =  ($showHidden)?'':' and df.hidden=0 ';
    $sql="Select fe.id as key1,   fe.* , df.id as key2 , df.* , if(fe.showed =-1, fe.showed,fe.showed) as showed , if(fe.showed =-1, fe.required,fe.required) as required ,if(fe.showed =-1, fe.group_behave ,fe.group_behave ) as group_behave From #__dtregister_fields as df inner join #__dtregister_field_event as fe on fe.field_id = df.id

			where fe.event_id=".$this->id." and (fe.showed in(1,3) or (fe.showed =-1 and df.showed in(1,3))) and df.published=1 ".$hidden_sql." order by ordering ";

		$this->db->setQuery($sql);
		
		$this->db->getErrorMsg();

		 $rowCustoms=$this->db->loadObjectList();
       
		return $rowCustoms;

	}
	function get_jeventdetail_id(){
	   $query = "select r.rp_id from #__jevents_repetition r where r.eventdetail_id = ".$this->id;
       $this->db->setQuery($query);
	   return $this->db->loadResult();

	}
	
}

class SyncJevent{

	var $db ;

	function SyncJevent(){

		$this->db = &JFactory::getDBO();

	}

	function getOld_events(){

		$query = "Select e.* , es.old_event_id from #__events as e left join #__dtregister_sync as es on e.id = es.old_event_id  ORDER BY publish_up desc ";

		 $this->db->setQuery($query);

		 return $this->db->loadObjectList();

	}

	function getNew_events(){

		 $query = "SELECT evdet_id  AS value, summary AS text, dtstart FROM #__jevents_vevdetail"

	        . "\n ORDER BY dtstart desc ";

		 $this->db->setQuery($query);

		 return $this->db->loadObjectList();

	}

	function sync($evtold,$evtnew){

		$evt_old = $this->last_sync_id($evtold,$evtnew);

		$evt_new = $evtnew ;

		$query = "Update #__dtregister_group_event set eventId=".$evt_new." where eventId = ".$evt_old;

		$this->db->setQuery($query);

		$this->db->query();

		$query = "Update #__dtregister_user set eventId=".$evt_new." where eventId = ".$evt_old;

		$this->db->setQuery($query);

		$this->db->query();

		$query = "Update #__dtregister_field_event set event_id=".$evt_new." where event_id = ".$evt_old;

		$this->db->setQuery($query);

		$this->db->query();

		$query = "Update #__dtregister_events_codes set event_id=".$evt_new." where event_id = ".$evt_old;

		$this->db->setQuery($query);

		$this->db->query();

		$this->new_sync_id($evtold,$evtnew);

		return true ;

	}

	function new_sync_id($evtold,$evtnew){

		   $query = "SELECT * FROM #__dtregister_sync where old_event_id = ".$evtold ;

	       $this->db->setQuery($query);

		   $this->db->query();

		   if($this->db->getNumRows() == 0 ){

			   $query = "insert #__dtregister_sync set old_event_id=".$evtold." , new_event_id=".$evtnew; 

			   $this->db->setQuery($query);

			   $this->db->query();

		   }else{

		       $query = "Update  #__dtregister_sync set  new_event_id=".$evtnew." where old_event_id=".$evtold." "; 

			   $this->db->setQuery($query);

		   	   $this->db->query();

		   }

	}

	function last_sync_id($evtold,$evtnew){

		 $query = "SELECT * FROM #__dtregister_sync where old_event_id = ".$evtold ;

	       $this->db->setQuery($query);

		   $this->db->query();

		   if($this->db->getNumRows() == 0 ){

		   		return $evtold ; 

		   }else{

		   		$row =  $this->db->loadObject();

				return $row->new_event_id ; 

		   }

	   }  

	  function is_sync($evtold){

		 $query = "SELECT * FROM #__dtregister_sync where old_event_id = ".$evtold ;

	       $this->db->setQuery($query);

		   $this->db->query();

		   if($this->db->getNumRows() == 0 ){

		   		return false ; 

		   }else{

		   		//$row =  $this->db->loadObject();

				return true ; 

		   }

	}

}

jimport('joomla.html.pagination');

class DtPagination extends JPagination{

	function __construct($total, $limitstart, $limit){

        global $mainframe ;

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );

		parent::__construct($total, $limitstart, $limit);

	}

	function getPagesLinks()

	{

		global $mainframe;

		$lang =& JFactory::getLanguage();

		// Build the page navigation list

		$data = $this->_buildDataObject();

		$list = array();

		$itemOverride = false;

		$listOverride = false;

		/* $chromePath = JPATH_THEMES.DS.$mainframe->getTemplate().DS.'html'.DS.'pagination.php';

		if (file_exists($chromePath))

		{

			require_once ($chromePath);

			if (function_exists('pagination_item_active') && function_exists('pagination_item_inactive')) {

				$itemOverride = true;

			}

			if (function_exists('pagination_list_render')) {

				$listOverride = true;

			}

		}*/

		// Build the select list

		if ($data->all->base !== null) {

			$list['all']['active'] = true;

			$list['all']['data'] = ($itemOverride) ? pagination_item_active($data->all) : $this->_item_active($data->all);

		} else {

			$list['all']['active'] = false;

			$list['all']['data'] = ($itemOverride) ? pagination_item_inactive($data->all) : $this->_item_inactive($data->all);

		}

		if ($data->start->base !== null) {

			$list['start']['active'] = true;

			$list['start']['data'] = ($itemOverride) ? pagination_item_active($data->start) : $this->_item_active($data->start);

		} else {

			$list['start']['active'] = false;

			$list['start']['data'] = ($itemOverride) ? pagination_item_inactive($data->start) : $this->_item_inactive($data->start);

		}

		if ($data->previous->base !== null) {

			$list['previous']['active'] = true;

			$list['previous']['data'] = ($itemOverride) ? pagination_item_active($data->previous) : $this->_item_active($data->previous);

		} else {

			$list['previous']['active'] = false;

			$list['previous']['data'] = ($itemOverride) ? pagination_item_inactive($data->previous) : $this->_item_inactive($data->previous);

		}

		$list['pages'] = array(); //make sure it exists

		foreach ($data->pages as $i => $page)

		{

			if ($page->base !== null) {

				$list['pages'][$i]['active'] = true;

				$list['pages'][$i]['data'] = ($itemOverride) ? pagination_item_active($page) : $this->_item_active($page);

			} else {

				$list['pages'][$i]['active'] = false;

				$list['pages'][$i]['data'] = ($itemOverride) ? pagination_item_inactive($page) : $this->_item_inactive($page);

			}

		}

		if ($data->next->base !== null) {

			$list['next']['active'] = true;

			$list['next']['data'] = ($itemOverride) ? pagination_item_active($data->next) : $this->_item_active($data->next);

		} else {

			$list['next']['active'] = false;

			$list['next']['data'] = ($itemOverride) ? pagination_item_inactive($data->next) : $this->_item_inactive($data->next);

		}

		if ($data->end->base !== null) {

			$list['end']['active'] = true;

			$list['end']['data'] = ($itemOverride) ? pagination_item_active($data->end) : $this->_item_active($data->end);

		} else {

			$list['end']['active'] = false;

			$list['end']['data'] = ($itemOverride) ? pagination_item_inactive($data->end) : $this->_item_inactive($data->end);

		}

		if($this->total > $this->limit){

			return ($listOverride) ? pagination_list_render($list) : $this->_list_render($list);

		}

		else{

			return '';

		}

	}

	function _item_active(&$item)

	{

		global $mainframe;

		if ($mainframe->isAdmin())

		{

			if($item->base>0)

				return "<a title=\"".$item->text."\" onclick=\"javascript: document.adminForm.limitstart.value=".$item->base."; submitform();return false;\">".$item->text."</a>";

			else

				return "<a title=\"".$item->text."\" onclick=\"javascript: document.adminForm.limitstart.value=0; submitform();return false;\">".$item->text."</a>";

		} else {

			if($item->base>0)

				return "<a title=\"".$item->text."\" onclick=\"javascript: document.frmcart.limitstart.value=".$item->base."; document.frmcart.submit();return false;\">".$item->text."</a>";

			else

				return "<a title=\"".$item->text."\" onclick=\"javascript: document.frmcart.limitstart.value=0; document.frmcart.submit();return false;\">".$item->text."</a>";

			//return "<a title=\"".$item->text."\" onclick=\"javascript: document.frmcart.limitstart.value=0; submitform();return false;\">".$item->text."</a>";

			//return "<a title=\"".$item->text."\" href=\"".$item->link."\" class=\"pagenav\">".$item->text."</a>";

		}

	}

}
class Member{

  var $id ;
  
  function Member($id=""){
     $this->id = $id ;   
	 $database = &JFactory::getDBO();
     $this->db = &$database;
  }
  
  function read(){
      $sql = "select * from #__dtregister_group_member where groupMemberId=".$this->id." " ;
	   $this->db->setQuery($sql);

	   $data = $this->db->loadObject(); 
	   foreach($data as $key=>$value){
	     $this->$key = $value;
	   }
  }
  function getUserId(){

	 $sql = "select useid from #__dtregister_group where groupId=".$this->groupUserId." limit 1 " ;
	 $this->db->setQuery($sql);
	 return $this->db->loadResult();
	 
  }
  function set($data){
	   
	   $database = &JFactory::getDBO();
       $this->db = &$database;
	   $fields = $this->db->getTableFields('#__dtregister_group_member');
	   
	   foreach($fields['#__dtregister_group_member'] as $field=>$type){
	       if(isset($data[$field])){
		     if(is_array($data[$field])){
			    $data[$field] = implode(",",$data[$field]);
			 }
			 
		     $this->$field = $data[$field];
		  }else{
		     
		  }
	   }
	   
	}
	 function save($data){
	  
	    $fields = $this->db->getTableFields('#__dtregister_group_member');
		foreach($fields['#__dtregister_group_member'] as $field=>$type){
	      if(isset($data->$field) && $data->$field !=""){
		     $sql = "update #__dtregister_group_member set $field=".$this->db->Quote($data->$field)." where groupMemberId=".$this->id ;
			 $this->db->setQuery($sql);
			 echo "<br>".$this->db->getQuery($sql);
			 $this->db->query();
			 echo "<br>".$this->db->getErrorMsg();
		  }else{ 
		     
		  }
	   }
	  
	}
	 function add($data){
	  
	    $fields = $this->db->getTableFields('#__dtregister_group_member');
		foreach($fields['#__dtregister_group_member'] as $field=>$type){
	      if(isset($data->$field) and $data->$field!=""){
		     $sql[] = " $field= ".$this->db->Quote($data->$field). " ";
			
		  }else{ 
		     
		  }
	   }
	   $sql = "insert #__dtregister_group_member set ".implode(",",$sql) ;
	    $this->db->setQuery($sql);
		echo "<br />".$this->db->getQuery($sql);
		$this->db->query();
		$sql = "update #__dtregister_group_amount set numberOfPerson = (numberOfPerson+1) where groupId=".$this->groupUserId;
	  $this->db->setQuery($sql);
	  echo "<br />".$this->db->getQuery($sql);
	  
	  $this->db->query();
		
	}
	
	function delete(){
	  
	  if(!isset($this->groupUserId))
	  $this->read();
	  $sql = "DELETE FROM #__dtregister_group_member WHERE groupMemberId=".$this->id;
	   $this->db->setQuery($sql);
	  echo "<br />".$this->db->getQuery($sql);
	  $this->db->query();
	  echo  $this->db->getErrorMsg();
	  $sql = "update #__dtregister_group_amount set numberOfPerson = (numberOfPerson-1) where groupId=".$this->groupUserId;
	  $this->db->setQuery($sql);
	  echo "<br />".$this->db->getQuery($sql);
	  
	  $this->db->query();
	  echo  $this->db->getErrorMsg();
	}

}

class CsvExport {
   
   var $group = array();
   
   var $individual = array();
   
   var $general = array();
   
   var $events = array();
   
   var $required =  array('register_date','summary','dtstart','userId');
   
   var $map_fields = array(
                      'firstname'=>'userFirstName',
					  'lastname'=>'userLastName',
					  'title'=>'userTitle',
					  'organization'=>'userOrganization',
					  'address'=>'userAddress',
					  'address2'=>'userAddress2',
					  'city'=>'userCity',
					  'state'=>'userState',
					  'email'=>'userEmail',
					  'zip'=>'userZip',
					  'country'=>'userCountry',
					  'phone'=>'userPhone',
					  'paid'=>'pay_later_paid'
					  
					  );
   var $map_header = array(
                      
					  'user_id'=>'Joomla UserId',
					  'register_date'=>'Register date',
					  'summary'=>'Event ',
					  'userId'=>'DT UserId',
					  'dtstart' =>'Event date',
					  'cancel' =>'Status',
					  
                      
                     );
   
   
   var $sortorder ;
   
   var $header ;
   
   function CsvExport(){
      $this->db = &JFactory::getDBO();
	  $this->_cancelTxt = array(JText::_( 'DT_ACTIVE' ),JText::_( 'DT_CANCELLED' ),JText::_( 'DT_PENDING' ));
	  $this->_attendTxt = array(JText::_( 'DT_NOT_ATTENDED' ),JText::_( 'DT_ATTENDED' ));
   }
   
   function getHeader(){
      $csv_header = array();
	  foreach($this->header as $field){
	     if(isset($this->map_header[$field])){
		   $csv_header[] = $this->map_header[$field] ;
		 }else{
		    $csv_header[] = $field ;
		 }
	  }
	   return $csv_header ;
   }
   
   function getFields(){
      
	    $sql="Select * From #__dtregister_export_fields";

		$this->db->setQuery($sql);
	
		$fieldsetting=$this->db->loadObjectList();
	
		$this->group = explode(",",$fieldsetting[0]->group_export_fields);
	
		$this->individual = explode(",",$fieldsetting[0]->individual_export_fields);
	
		$this->general = explode(",",$fieldsetting[0]->general_export_fields);

   }
   
   function mapRow($row,$type='I'){
     
	 global $lang_var ;
	 $filter_row = (object) array();
	 	
	  switch ($type){
	     case 'I':
		   if(count(array_filter($this->individual))<=0){
			    return array();
			 }
		      $dt_evt = new Event($row->eventId);
	          $category = new mosDtCategory($this->db) ;
	          $category->load($dt_evt->category);
	          $row->category = $category->categoryName;
			  $location = $dt_evt->get_location();
			  if(isset($location->name)){
			     $row->location  = $location->name;
			  }else{
			     $row->location = "";
			  }
			  $row->amount = numberFormat($row->amount,2);
			  if($row->user_id==0){
			     $row->user_id = '' ;
			  }
			if($row->payment_type=='Pay Later'){
		
				$paylater_values = array(1=>'At_door',2=>'Mail',3=>'Phone');
		
				$row->payment_type = $paylater_values[$row->pay_later_option];
		
			}
			$row->payment_type = $lang_var[$row->payment_type];
		     foreach($this->header as $field){
			    if($field == 'payment_type'){

						if($row->payment_type=='Pay Later'){

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

							//$row->payment_type = $paylater_values[$row->pay_later_option];

						}
				}
				
				if($field == 'register_date'){
				   $row->register_date  = get_date($row->register_date);
				}
				
				if($field == 'dtstart'){
				   $row->dtstart  = get_date($row->dtstart);
				}
                if($field == 'cancel'){
				    
					$row->cancel = $this->_cancelTxt[$row->cancel];
				}
				if($field == 'attend'){
				    
					$row->attend = $this->_attendTxt[$row->attend];
				}
				//$row->payment_type = $lang_var[$row->payment_type];
			    if(in_array('general',$this->sortorder[$field]) || in_array('required',$this->sortorder[$field]) || (in_array('individual',$this->sortorder[$field]) &&in_array($field,$this->individual) ) ){
				   if(isset($this->map_fields[$field])){
				      
				      $data_key = $this->map_fields[$field] ;
				   }else{
				      $data_key = $field ;
				   }
				   if($field=='paid'){
					      
						 $row->$data_key = ($row->$data_key == 1)?JText::_('DT_PAID'):JText::_('DT_NOT_PAID');
						  
					}
				   $filter_row->$field = stripslashes($row->$data_key);
				}else{
				   $filter_row->$field = '' ;
				}
			 }
		 break;
		 case 'G':
		 
			 if(count(count(array_filter($this->group)))<=0){
			    return array();
			 }
		     foreach($this->header as $field){
			     if(in_array('group',$this->sortorder[$field]) && in_array($field,$this->group)){
				    $filter_row->$field = $row->{$field} ;
				 }else{
				    $filter_row->$field = '' ;
				 }
			 }
		 break ;
	  }
	  
	  return $filter_row ;
	  
   }
   
   function getEvents(){
      
	  $sql="Select distinct eventId From #__dtregister_group_event where export=1";

	  $this->db->setQuery($sql);

	  $exportevents=$this->db->loadAssocList();
	  $exporteventList =  array();
	  if(is_array($exportevents))
	
		foreach($exportevents as $value){
	
			$exporteventList[] = $value['eventId'];
	
		}
		$this->events = $exporteventList ;
	   return $exporteventList ;
	  
   }
   
   function mergeHeader(){
      $this->getFields();
	  $this->sortFields();
	  
	  $header = array() ;
	  foreach($this->sortorder as $field => $types){
	     
		 foreach($types as $type){
		    
			if(in_array($field,$this->$type)){
			   $header[] = $field ;
			   break ;
			}
			
		 }
		 
	  }
	  $this->header = $header ;
	  return $header ;
	  
   }
   
   function sortFields(){
       
       $order =  array(
	       'user_id'  => array('general'),
	       'register_date' => array('required'),
		   'summary' => array('required'),
		   'category' => array('general'),
		   'location' => array('general'),
		   'dtstart' => array('required'),
		   'userType' =>array('general'),

		   'userId' =>array('required'),
		   'title' => array('group','individual'),
		   'firstname' => array('group','individual'),
		   'lastname'  => array('group','individual'),
		   'organization'  => array('group','individual'),
		   'address'   => array('group','individual'),
		   'address2'   => array('group','individual'),
		   'city'   => array('group','individual'),
		   'state'   => array('group','individual'),
		   'zip'   => array('group','individual'),
		   'country'   => array('group','individual'),
		   'email'   => array('group','individual'),
		   'phone' => array('group','individual'),
		   'paid_amount' => array('individual'),
		   'amount' =>array('general'),
		   'payment_type' => array('general'),
		   'paid' => array('general'),
		   'groupId' => array('general'),
		   'numberOfPerson' => array('general'),
		   'confirmNum' => array('general'),
		   'code' => array('general'),
		   'cancel' => array('general'),
		   'attend' => array('general')
	   );
	   
	    $fields  = $this->getCustomFields();
		
		foreach($fields as  $field){
		   $this->group[]      = $field->name;
		   $this->individual[] = $field->name;
		   $order[$field->name] =  array('group','individual');
		   
		}
		
		$this->sortorder = $order;
	   
   }
   
   function getCustomFields(){
      $sql="Select * From #__dtregister_fields  where type<>6 and published=1 and (	export_individual = 1 or export_group = 1)  order by ordering";

	  $this->db->setQuery($sql);

	  return $rowCustoms=$this->db->loadObjectList();
   }
   
   function output($csv_output){
     	if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {

			$UserBrowser = "Opera";

		}

		elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {

			$UserBrowser = "IE";

		} else {

			$UserBrowser = '';	
		}
		$mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';

		$filename = "BackupList_Registrations";
		
		header('Content-Type: ' . $mime_type);

			header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');

			if ($UserBrowser == 'IE') {

				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');

				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

				header('Pragma: public');

			}

			else {

				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');

				header('Pragma: no-cache');

			}

			print $csv_output;

			exit();

   }

}
class DTConfig{
      
	   function DTConfig(){
		  $this->db = &JFactory::getDBO();
	   }
	  
	  function arrangeJoomfishKey($old_keys =  array() , $new_keys = array()){
	      
		  foreach($old_keys as $confKey => $old_key){
		     
			 if($old_key != $new_keys[$confKey]){
			     
				 $query = "Update #__jf_content set reference_id=".$new_keys[$confKey]." where reference_table='dtregister_config' and reference_id = $old_key ";
				 $this->db->setQuery($query);
				 if(!$this->db->query()){
			        echo $this->db->getErrorMsg();
				 }
				 
			 }
			 
		  }
	         
	  }
	  
	  function getJoomfishKeys(){
	     
		 $query = " SELECT * 
		 	FROM `#__dtregister_config`
		 	WHERE config_key
		 	IN (
		 	'thanksmsg',
		'pay_later_thk_msg',
		'thanksemail',
		'full_message',
		'cut_off_date_message',
		'waiting_msg',
		'terms_conditions_msg',
		'private_event_msg',
		'prerequisite_event_msg',
		'overlap_event_msg',
		'registrant_message',
		'userpanelmessage',
		'subthanksemail',
		'email_cancel_confirm' ,
		'email_change_confirm',
		'payment_confirm',
		'status_change_msg',
		'subchangestatusemail',
		'paid_status_change_msg',
		'subpaidstatusemail',
		'registrant_message',
		'upsubpaymentemail',
		'upsubcancelemail',
		'upsubchangeemail'
		 	)" ;
		 	
		 $this->db->setQuery($query);
		 
		 $configs = $this->db->loadObjectList();
		 $keys = array();
		
		 foreach($configs as $config){
		    
			$keys[$config->config_key] = $config->id ;
			
		 }
		 
		 return $keys ;
		 
	  }
	  
	  function joomfish_fix(){
	      $query = " SELECT * 
		 	FROM `#__dtregister_config`
		 	WHERE config_key
		 	IN (
		 	'thanksmsg',
		'pay_later_thk_msg',
		'thanksemail',
		'full_message',
		'cut_off_date_message',
		'waiting_msg',
		'terms_conditions_msg',
		'private_event_msg',
		'prerequisite_event_msg',
		'overlap_event_msg',
		'registrant_message',
		'userpanelmessage',
		'subthanksemail',
		'email_cancel_confirm' ,
		'email_change_confirm',
		'payment_confirm',
		'status_change_msg',
		'subchangestatusemail',
		'paid_status_change_msg',
		'subpaidstatusemail',
		'registrant_message',
		'upsubpaymentemail',
		'upsubcancelemail',
		'upsubchangeemail'
		 	)" ;
		 	
		 $this->db->setQuery($query);
		 
		 $configs = $this->db->loadObjectList();
		 $keys = array();
		
		 foreach($configs as $config){
		    $query = "select jf1.* from `#__jf_content` jf1 inner join `#__jf_content` jf2 on jf1.reference_id = jf2.reference_id and jf2.value='".$config->config_key."'   where jf1.reference_table='dtregister_config' and  jf2.reference_table='dtregister_config' " ;
			$keys[$config->config_key] = $config->id ;
			$this->db->setQuery($query);
			$this->db->getQuery($query);
			$jfrows = $this->db->loadObjectList();
			if($jfrows){
			    foreach($jfrows as $jfrow){
				     $query = "Update #__jf_content set reference_id=".$config->id." where id =  ".$jfrow->id;
					 $this->db->setQuery($query);
					 $this->db->getQuery($query);
					 if($config->id != $jfrow->reference_id)
					 if(!$this->db->query()){
						echo $this->db->getErrorMsg();
					}
				}
			}
			
		 }
		 
	  }
	  
	  function getConfig($key){
	     
		 $sql = "select config_value from #__dtregister_config where config_key='$key'";
	  
	     $this->db->setQuery($sql);
		
		 return $this->db->loadResult();
	  }
	  
	   function setConfig($key,$value){
	     
		 $sql = "Update #__dtregister_config set config_value=$value  where config_key='$key'";
	  
	     $this->db->setQuery($sql);
		
		 return $this->db->query();
	  }
	  
	  function updateEventorder($order=0){
	     
		 if($order==1){
	  
		   $ordering = " b.dtstart desc  ";
		}else if($order==2){
		   $ordering = " b.dtstart asc  ";
		}elseif($order==3){
			 $ordering = " b.summary asc  ";
		}else{
		   return ;
		   $ordering = " a.ordering ASC ";
		}

		$sql ="SELECT a. *

		FROM #__dtregister_group_event as  a
        LEFT JOIN #__dtregister_categories as c ON a.category = c.categoryId 
		
		INNER JOIN #__jevents_vevdetail as b ON a.eventid = b.evdet_id
		
		";
        
        $sql .= "group by eventId order by c.ordering ,$ordering " ;
		
		$this->db->setQuery($sql);
		
		$events = $this->db->loadObjectList();
		
		$category = 0;
		$ordering = 1 ;
		if(is_array($events))
		foreach($events as $event){
		   if($event->category != $category){
		      $ordering = 1 ;
			  $category = $event->category ;
		   }
		   $evt =  new Event($event->eventId);
		   $evt->save_field('ordering',$ordering);
		   unset($evt);
           $ordering ++ ;
		}
		
	  }
	  
   }
   
class DTHTML extends JHTML{
    
	function tooltip($tooltip, $title='', $image='tooltip.png', $text='', $href='', $link=1,$class='DtTip'){
	    
		$tip =  parent::tooltip($tooltip, $title='', $image='tooltip.png', $text='', $href='', $link=1);
		
		return str_replace('hasTip',$class,$tip);
		
		
	}
	
}

class DTbarcode{
	
   function DTbarcode($text="Testing",$filename=""){
	    global $barcode_type , $barcode_image_type , $barcodeDpi , $barcodeThick , $barcode_resolution , $barcode_font_size,$barcode_checksum ,$barcode_rotation ,$barCodeImagetypeToExt;
		$barcode_checksum = 0 ;
		include( JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
		$class_dir = JPATH_SITE.'/components/com_dtregister/lib/barcode/class';
		$filename = ($filename!="")?JPATH_SITE.'/images/dtregister/barcode/'.$filename.'.'.$barCodeImagetypeToExt[$barcode_image_type]:'' ;
		
	    require_once($class_dir . '/color.php');
	    require_once($class_dir . '/barcode.php');
	    require_once($class_dir . '/drawing.php');
	    require_once($class_dir . '/font.php');
		require_once($class_dir . '/'.$barcode_type.'.php');
		$this->font = new BCGFont(JPATH_SITE . '/components/com_dtregister/monofont.ttf', intval($barcode_font_size));
		$this->color_black = new BCGColor(0, 0, 0);
		$this->color_white = new BCGColor(255, 255, 255);
		$codebar = 'BCG' . $barcode_type;
		$this->code_generated = new $codebar();
		
		if($barcode_checksum && intval($barcode_checksum) === 1)
		  $this->code_generated->setChecksum(true);
		  
		$this->code_generated->setLabel($text);
		$this->code_generated->setThickness($barcodeThick);
		$this->code_generated->setScale($barcode_resolution);
		$this->code_generated->setBackgroundColor($this->color_white);
		$this->code_generated->setForegroundColor($this->color_black);
		$this->code_generated->setFont($this->font);
		
		$this->code_generated->parse($text);
		
		$this->drawing = new BCGDrawing($filename, $this->color_white);
		$this->drawing->setBarcode($this->code_generated);
		$this->drawing->setRotationAngle($barcode_rotation);
		$this->drawing->setDPI(($barcodeDpi == 'null' || $barcodeDpi=="" )? null : (int)$barcodeDpi);
		
		$this->drawing->draw();
		  
		
   }	
   
   function preview(){
	   global $barcode_image_type , $barCodeImagetype;
	   include( JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
	  if( $this->drawing->filename==""){
	   if($barcode_image_type == 'png') { 
			header('Content-Type: image/png');
		} elseif($barcode_image_type == 'jpg') {
			header('Content-Type: image/jpeg');
		} elseif(intval($_GET['o']) === 3) {
			header('Content-Type: image/gif');
		}
	  }
        $temp =  array_flip(array_keys($barCodeImagetype));
		
        $this->drawing->finish($temp[$barcode_image_type]);
   }
   
   function save(){
	     
   }
}

?>