<?php

/**
* @version 2.6.7
* @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
*/

//error_reporting(E_ALL | ~E_STRICT);

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );
global $now , $month_arr ,$lang_var ,$custom_field_types;
jimport('joomla.utilities.date');
 JHTML::_('behavior.calendar');
  $custom_field_types = array(
            0=>'Text',
            1=>'Dropdown',
			2=>'Texarea',
			3=>'Checkbox',
			4=>'Radio',
			5=>'Date',
			6=>'Textual',
			7=>'Upload'
            );
$now = new JDate('now');
$config =& JFactory::getConfig();
$now->setOffset($config->getValue('config.offset'));
$lang_var = array('PayPal'=>JText::_('PAYPAL'),'Paypal'=>JText::_('PAYPAL'),'Authorize.net'=>JText::_('AUTH_NET'),'Echeck'=>JText::_('ECHECK'),'Mail'=>JText::_('DT_MAILIN_PAYMENT'),

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

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

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

require_once( JPATH_SITE.'/components/com_dtregister/common.php');
$lang =& JFactory::getLanguage();
require_once( $mainframe->getPath( 'admin_html' ) );

$cid  = JRequest::getVar( 'cid', array(0), 'request', 'array' );

$gid = JRequest::getVar( 'gid' );

$uid = JRequest::getVar( 'uid' );

$id = JRequest::getVar( 'id' );

$act = JRequest::getVar( 'act' );

switch ($act) {
    
	
	case "settings":

		$task = "settings";

		break;

	case "registrations":

		$task = "listregistrations";

		break;

		//Custom Fields

	case "custom_fields":

		$task="custom_fields";

		break;

	case "full_event":

		$task="show_event_waiting";

		break;

	case "event_email":

		$task="show_event_email_form";

		break;

	case "save":

		$task="save";

		break;

  case "categories":

		$task = "manage_categories";

		break;

}

require_once( $mainframe->getPath( 'toolbar_html' ) );

switch ($task) {
	case "barcodepreview":
	   
	   barcodepreview();
	   
	 break ;
    case 'deletegrpmember':
	  deletegrpmember($option,$cid) ;
	break ;
    case 'loadtab':
	  loadtab();
	break; 
    case 'fileupload':
       ob_clean();
	   fileupload();
	   die;
    break;
	case "remove_file";

		removeFile($option);

	break ;
    case 'addgroupmember':
	  addgroupmember();
	break ;
	case "editgroupmember":

		editgroupmember($option,$cid);

	break;

	case "export":

		doexportCSV($option);

		break;

	case "editmember":

		editmember($option,$cid[0]);

		break;

	case 'newmember':

		newMember($option);

		break;

	case "editmemberA":

		editmember($option,$id);

		break;

	case "deletemember":

		deletemember($option,$cid);

		break;

	case 'save_new_member':

		saveNewMember($option);

		break;

	case 'cancel_new_member':

		cancelNewMember($option);

		break;

	case "savemember":

		savemember($option,$uid);

		break;

	case "add":

		newGroups( $option, 0 );

		break;

    case "copyEvent" :

	    copyEvent($option, $cid[0]  );

	 break ;
  
   case "copyField" :

         copyField($option, $cid[0]  );
    break;
	case "listregistrations":

		listregistrations($option);

		break;

	case 'showmembers':

		showmembers($option,$gid);

		break;

	case "edit":

		editGroups( $option, $cid[0] );

		break;

	case "save":

		saveGroups( $option );

		break;

    case "applyevent":

		saveGroups( $option );

		break;

	case "remove":

		removeGroups( $cid, $option );

		break;

	case "cancel":

		cancelGroups( $option );

		break;

	case "settings":

		showConfig( $option );

		break;

	case "savesettings":

		saveConfig ($option, $cardtype, $cardtext,$thankmsg);

		break;
   case "applysettings":
        saveConfig ($option, $cardtype, $cardtext,$thankmsg);
   break;
		//Here are code for event waiting

	case 'detail_event_waiting':

		viewEventWaiting($option, $cid[0]);

		break;

	case 'remove_event_waiting':

		removeEventWaiting($option, $cid);

		break;

	case 'show_event_waiting':

		showEventWaiting($option);

		break;

		//Here are custom field sections

		//Custom fields section

	case 'new_customfield':

		editCustomfield( $option, 0 );

		break;

	case 'edit_customfield':

		editCustomfield( $option, $cid[0] );

		break;

	case 'editA_customfield':

		editCustomfield( $option, $id );

		break;

	case 'save_customfield':

		saveCustomfield( $option );

		break;

	case 'remove_customfield':

		removeCustomfield( $cid, $option );

		break;

	case 'publish_customfield':

		publishCustomfield( $cid, 1, $option );

		break;

	case 'unpublish_customfield':

		publishCustomfield( $cid, 0, $option );

		break;
    case 'fieldoptions':
	   
	   fieldoptions();
	   
	break;
	case 'publish_event':

		publishEvent( $cid, 1, $option );

		break;

	case 'unpublish_event':

		publishEvent( $cid, 0, $option );

		break;
   	case 'archive_event':

		archiveEvent( $cid, 1, $option );

		break;
    case 'unarchive_event':
	   archiveEvent( $cid, 0, $option );
	break;
	case 'cancel_customfield':

		cancelCustomfield( $option );

		break;

	case 'orderup_customfield':

		orderCustomfield( intval( $cid[0] ), -1, $option );

		break;

   case 'orderup_event':

		reorderEvent( intval( $cid[0] ), -1, $option );

		break;

	case 'orderdown_event':

		reorderEvent( intval( $cid[0] ), 1, $option );

		break;

	 case 'orderup_category':

		reorderCategory( intval( $cid[0] ), -1, $option );

		break;

	case 'orderdown_category':

		reorderCategory( intval( $cid[0] ), 1, $option );

		break;

   case 'saveorder_category':

	   saveOrderCategory($option,$cid);

	   break;

	case 'saveorder_event':

		saveOrderEvent($option,$cid);

		break;

	case 'orderdown_customfield':

		orderCustomfield( intval( $cid[0] ), 1, $option );

		break;

	case 'saveorder_customfield':

		saveOrderCustomfield($option,$cid);

		break;

	case 'custom_fields':

		showCustomFields( $option );

		break;

	case 'show_event_email_form':

		showEventEmailForm($option);

		break;

	case 'send_mail':

		sendMailToMembers($option);

		break;

	case 'new_group_registration':

		newGroupRegistration($option);

		break;

	case 'members_detail':

		membersDetail($option);

		break;

	case 'group_registration_form':

		groupRegistrationForm($option);

		break;

	case 'save_group_registration':

		saveGroupRegistration($option);

		break;

	case "cancel_registration":

		cancelRegistration($option);

		break;

	case 'paid':

		payLaterPaid($option,$cid,1);

		break;

	case 'un_paid':

		payLaterPaid($option,$cid,0);

		break;

    case 'manage_categories':

        mycategories($option);

		break;

    case 'newcategory':

		newcategory($option);

		break;

   case 'cancelnewcategory':

		cancelnewcategory($option);

		break;

    case "editcategory":

		editcategory($option);

		break;

    case "savecategory":

		savecategory($option);

		break;

    case "savenewcategory":

		savenewcategory($option);

		break;

	case "deletecategory":

		deletecategory($option,$id);

		break;
		
    case 'deletecategories':
	   
	   deletecategories();
	   
	break;

   case "save_group_member" :

		saveGroupMember($option);

	break;

    case "export_event_settings":

		exportEventSettings($option);

	break;

	case 'save_event_export_setting':

		saveEventExportSetting($option);

	break;

	case 'save_field_export_setting':

		saveFieldExportSetting($option);

	break;

	case 'discount_codes':

		listdiscountcodes($option);

	break;

	case 'new_discount_code':

		newDiscountCode($option);

	break;

	case 'save_discount_code':

		saveDiscountCode($option);

	break;

	case 'unpublish_discountcode':

		publishDiscountCode(0);

	break;

	case 'publish_discountcode':

		publishDiscountCode(1);

	break;

	case 'edit_discount_code':

		editDiscountCode($option);

	break;

	case 'delete_discountcode':

		deleteDiscountcode($option);

	break;

	case 'getcategory':

		getcategory($option);

	break;

	case 'getarticle':

		getarticle($option);

	break ;

 	case 'savesync':

   		savesync($option);

    break;

	case "sync":

		showsync($option);

	break;

    case "groupPublish":

	   groupPublish($option,1);

	break;
	
	case "UngroupPublish":
	  
	  groupPublish($option,0);
	
    break;
    case "locations":

	   listlocation($option);

	break;

	case "newlocation":

	  addlocation($option);

    break ;

	case "cancelLocation":

	   listlocation($option);

	break;

	case "locationImageUpload" :

	  locationImageUpload($option);

	break ;

	case "savelocation" :

	  savelocation($option);

	break ;

	case "editlocation" :

	  editlocation($option);

	break ;

	case 'deletelocation':

	  deletelocation($option);

	break;

	case 'thumb':

	  thumb($option);

	break;

	case 'attended':

		eventAttended($option,$cid,1);

		break;

	case 'un_attended':

		eventAttended($option,$cid,0);

		break;
    case 'getconditonField':
	
	    getconditonField();
	   die('good');
	
	break ;
	case 'resendthkemail':
	   resendThanksEmail();
	break ;
	default:

		showGroups( $option );

		break;

}

/*

# Main functions start here ##################################################

*/

function resendThanksEmail(){
	global $mainframe ;
	$cid  = JRequest::getVar( 'cid', array(0), 'request', 'array' );
	foreach($cid as $userId){
	   	registration_email_only_user($userId);
	}
	$mainframe->redirect("index.php?option=com_dtregister&task=listregistrations",JText::_('DT_THANKS_EMAIL_SENT'));
	
}

function fileupload(){
   $type = trim( JRequest::getVar('type', '','request' ) );
   $vars =  explode('|',$type);
   $name = $vars[0];
   $size = $vars[1];
   $types = explode(",",$vars[2]);
   $file = $_FILES["file_".$name];
 
   $newtype = array();
   foreach($types as $type){
      $newtype[] = ".".$type;
   }
   foreach($newtype as $val){
      $types[] = $val;
   }
    echo "<pre>";
	print_r($_POST);
	print_r($_FILES);
   print_r($file);
   print_r($types);
  echo "</pre>";
   $dt_file = new DT_file();
   jimport('joomla.filesystem.file');
   $ext = JFile::getExt($file['name']);
   
   if(in_array($ext,$types) || count($types) <1){
	   if(($file['size']/1000) <= $size){
	      $dt_file->upload($file,'uploads');
		  $value=$dt_file->path;
		  ?>
          <script>
		     parent.DTjQuery('#<?php echo $name;?>').val('<?php echo JFile::getName($dt_file->path) ?>');
			  parent.DTjQuery('#<?php echo $name;?>').before(parent.document.createTextNode("<?php echo JText::_( 'DT_FILE_UPLOADED' ) ?>"));
		  </script>
          <?php
	    }else{// file error
		   ?>
            <script>
		      alert('<?php echo JText::_( 'DT_ERROR_FILE_SIZE' ); ?>');
		  </script>
           <?php
		}
	}else{// file type not valid
	     ?>
            <script>
		      alert('<?php echo JText::_( 'DT_ERROR_FILE_TYPE' ); ?>');
		   </script>
           <?php    
	}		  		   
   
   die;
   
}
function thumb($option){

	ob_clean();

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

	include("../components/com_dtregister/thumbnail.inc.php");

	$thumb = new Thumbnail($_GET['filename']);

     $registrant_avatar_width = JRequest::getVar('w', $registrant_avatar_width ) ;

	 $registrant_avatar_height = JRequest::getVar('h', $registrant_avatar_height ) ;

    $thumb->resize($registrant_avatar_width,$registrant_avatar_height);

   $thumb->show();

   exit;

}

function savelocation($option){

   	global $mainframe;

    $database = &JFactory::getDBO();

    $row = new DTlocation( $database );

	$id=JRequest::getInt('id',0);

	if($id){

	   $row->load($id);

	}

	if(!isset($_POST['showimage'])){

	   $row->showimage = 0;

	}

	if (!$row->bind( $_POST )) {

        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";

        exit();

    }

    if (!$row->check()) {

        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";

        exit();

    }

    if (!$row->store()) {

		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";

        exit();

    }

	$mainframe->redirect( "index2.php?option=com_dtregister&task=locations" ,JText::_( 'DT_LOCATION_SAVED') );

}

function locationImageUpload($options){

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

 ob_clean();

	$file = $_FILES['locationimage'];

  $dt_file = new DT_file();

  if($dt_file->upload($file,'locations')){

  echo "DTjQuery('#image').val('".$dt_file->path."');\n";

    echo "DTjQuery('#showimag').html('<img src=\"../index.php?option=com_dtregister&w=".$location_img_w."&h=".$location_img_h."&task=thumb&no_html=1&filename=images/dtregister/locations/".basename($dt_file->path)."\" />');\n";

    echo "alert('".JText::_( 'DT_FILE_UPLOADED')  ."') ;";

  }else{

    echo "alert('".JText::_( 'DT_FILE_UPLOAD_ERROR')  ."');";

  }

}

function listlocation($option){

  global $mainframe;

  $database = &JFactory::getDBO();

  jimport('joomla.html.pagination');

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

  $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
$limitstart = JRequest::getVar('limitstart',0);
  $sql = "Select SQL_CALC_FOUND_ROWS * from #__dtregister_locations";

  $database->setQuery( $sql,$limitstart,$limit);

  $locations=$database->loadObjectList();

  $database->setQuery('SELECT FOUND_ROWS();');

  $pageNav = new JPagination( $database->loadResult(), $limitstart, $limit  );

  HTML_groups::listlocation($locations,$pageNav);

}

function editlocation(){

   	global $mainframe;

    $database = &JFactory::getDBO();

    $row = new DTlocation( $database );

	$id  = JRequest::getVar( 'cid', array(0), 'request', 'array' );

	if($id){

	   $row->load($id[0]);

	}

	HTML_groups::editlocation($row);

}

function fieldoptions(){
   
   $id  = JRequest::getVar( 'id',0);
   $database = &JFactory::getDBO();
   $row =  new mosField($database);
   $row->load($id);
   $list = explode('|',$row->values);
   $html = "";
   foreach($list as $key=>$option){
		
		  //$checked = (in_array($key,$values))? "checked":'';
		  $html .= '<input type="checkbox" name="selection_values[]" value="'.$key.'"  /> '.$option.'<br />' ; 
		  
    }
	echo $html ;
}

function deletelocation($option){

   global $mainframe;

   $locations  = JRequest::getVar( 'cid', array(0), 'request', 'array' );

   $database = &JFactory::getDBO();

   $location = new DTlocation( $database );

   foreach($locations as $id){

	  $location->delete($id);

   }

   $mainframe->redirect( "index2.php?option=com_dtregister&task=locations" ,JText::_( 'DT_LOCATION_DELETED') );

}

function addlocation($option){

   HTML_groups::addlocation();

}

function copyField($option, $cid  ){
    $database = &JFactory::getDBO();
	
	$database = &JFactory::getDBO();

	$row = new mosField( $database );

	// load the row from the db table
   $id = 0;
	$row->load( (int)$cid);
	
	//Published
    $row->id = 0;
	$row->name = "";
	if(!$id)

	{

		$row->published=1;

		$row->required=0;

	}

	//Added to suport multi field types

	//Get field types
	$field = new Custom_field($row->id);
	$field->read();
      $list = $field->parent_list();
   $parent_option =  array();
   
    $parent_option[]=JHTML::_('select.option','',JText::_('DT_SELECT'));
   foreach($list as $key=>$value){
       $parent_option[]=JHTML::_('select.option',$key,$value);
   }
	
	$lists =  array();
	$lists["parent_list"]=JHTML::_('select.genericlist', $parent_option,"parent_id","","value","text",$row->parent_id);
	$fieldTypes=array();

	$fieldTypes[]=JHTML::_('select.option',"0","Text");

	$fieldTypes[]=JHTML::_('select.option',"1","Dropdown");

	$fieldTypes[]=JHTML::_('select.option',"2","Texarea");

	$fieldTypes[]=JHTML::_('select.option',"3","Checkbox");

	$fieldTypes[]=JHTML::_('select.option',"4","Radio");

	$fieldTypes[]=JHTML::_('select.option',"5","Date");

	$fieldTypes[]=JHTML::_('select.option',"6","Textual");
    
	$fieldTypes[]=JHTML::_('select.option',"7","Upload");
	
	$lists["type"]=JHTML::_('select.genericlist', $fieldTypes,"type","onchange='changeFieldType(1);'","value","text",$row->type);

	//End added

	//New list

	if($row->type<3){

		$atttribute=' disabled=true ';

	} else {$atttribute='';}

	if($row->new_line==null)

		$row->new_line=0;

	$lists['new_line']=JHTMLSelect::booleanlist('new_line',$atttribute,$row->new_line);

	$lists['published']=JHTMLSelect::booleanlist('published',$atttribute,$row->published);

	$lists['required']=JHTMLSelect::booleanlist('required',$atttribute,$row->required);
	$lists['hidden']=JHTMLSelect::booleanlist('hidden',$atttribute,$row->hidden);
	$lists['allevent']=JHTMLSelect::booleanlist('allevent',$atttribute,$row->allevent);
    $lists['showed']=JHTMLSelect::booleanlist('showed',$atttribute,$row->showed);
   
    $options = array();
   
   $options[]=JHTML::_('select.option',"1",JText::_( 'DT_INDIVIDUAL' ));
   $options[]=JHTML::_('select.option',"2",JText::_( 'DT_GROUP' ));
   $options[]=JHTML::_('select.option',"3",JText::_( 'DT_BOTH'));
	$lists["showed"]=JHTML::_('select.radiolist', $options,"showed","","value","text",$row->showed);
   
   $options = array();
   
   $options[]=JHTML::_('select.option',"1",JText::_( 'DT_EACH_MEMBER' ));
   $options[]=JHTML::_('select.option',"2",JText::_( 'DT_BILLING_ONLY' ));
   $options[]=JHTML::_('select.option',"3",JText::_( 'DT_MEMBERS_BILLING'));
	$lists["group_behave"]=JHTML::_('select.radiolist', $options,"group_behave","","value","text",$row->group_behave);
	HTML_groups::editCustomfield($row, $option,$lists);

}

function  copyEvent($option,$uid){

 $database = &JFactory::getDBO();

  $aqry="SELECT a.*, b.summary from #__dtregister_group_event a, #__jevents_vevdetail b WHERE a.eventid=b.evdet_id and a.slabId= $uid";

  $database->setQuery($aqry);

  $res=$database->loadObject();

  HTML_groups::newGroups( $option, $uid, $res );

}

function groupPublish($option,$publish){

  global $mainframe ;

  $slabId = JRequest::getVar( 'cid' );
  
  $slabId = $slabId[0];
  
  $database = &JFactory::getDBO();
  
  $query = "select eventId from #__dtregister_group_event where slabId = ".$slabId. " limit 1"	;

			$database->setQuery($query);

			$eventId = $database->loadResult();
 
  $dt_evt  = new Event($eventId);

  $dt_evt->save_field('publish',$publish);

	unset($_REQUEST['task']);
	$_REQUEST['act'] = 'groups';
	
 $get_str = http_build_query($_REQUEST);

    $mainframe->redirect("index2.php?".$get_str);
  
  $mainframe->redirect("index.php?option=com_dtregister", JText::_( 'DT_STATUS_UPDATED'));

}

function removeFile($option){

	$id = $_REQUEST['id'];

	$dt_file =  new DT_file($id);

	$dt_file->remove();

}

function showsync($option){

	$sync =  new SyncJevent();

	$old = $sync->getOld_events();

	$new = $sync->getNew_events();

	HTML_groups::showsync($old , $new);

}

function savesync($option){

	$evtnew = $_REQUEST['evtnew'];

	$evtold = $_REQUEST['evtold'];

	$i  = $_REQUEST['messagenum'];

	$sync =  new SyncJevent();

	if($sync->is_sync($evtold) && $evtnew == ""){

		echo  JText::_( 'DT_SYNC');

		?>

        <script>

		    var i = <?php echo $i  ?> ;

			DTjQuery('.message:eq('+i+')').addClass('syncdone');

			DTjQuery('.message:eq('+i+')').removeClass('syncerror');

		</script>

        <?php

		exit ;

	}

	if($evtnew == ""){

		echo  JText::_( 'DT_ERROR_SELECT_EVENT');

		?>

        <script>

		    var i = <?php echo $i  ?> ;

			DTjQuery('.message:eq('+i+')').removeClass('syncdone');

			DTjQuery('.message:eq('+i+')').addClass('syncerror');

		</script>

        <?php

		exit ;

	}else{

		$sync->sync($evtold,$evtnew);

		echo  JText::_( 'DT_SYNC');

		?>

        <script>

		    var i = <?php echo $i  ?> ;

			DTjQuery('.message:eq('+i+')').addClass('syncdone');

			DTjQuery('.message:eq('+i+')').removeClass('syncerror');

		</script>

        <?php

	}

}

function getcategory($option){

	$database = &JFactory::getDBO();

	$sectionId = $_REQUEST['sectionId'];

	$options=array();

				$options[]=JHTML::_('select.option',"","Select Category");

				$query = "Select * from #__categories where section='".$sectionId ."'";

				$database->setQuery($query);

				$sections = $database->loadObjectList();

				foreach($sections as $section){

					$options[]=JHTML::_('select.option',$section->id,$section->title);

				}

			echo	$section_html =  JHTML::_('select.genericlist', $options,"categorylist","","value","text");

			?>

			<?php

			exit;

}

function getarticle($option){

	$database = &JFactory::getDBO();

	$categoryId = $_REQUEST['categoryId'];

	$options=array();

				$options[]=JHTML::_('select.option',"","Select Article");

				$query = "Select c.* from #__content c  where c.catid='".$categoryId ."'";

				$database->setQuery($query);

				$sections = $database->loadObjectList();

				foreach($sections as $section){

					$options[]=JHTML::_('select.option',$section->id,$section->title);

				}

			echo	$section_html =  JHTML::_('select.genericlist', $options,"article_id","","value","text");

			?>

			<?php

			exit;

}

function saveGroupMember($option){

	global $database,$mosConfig_live_site,$mosConfig_absolute_path,$DT_mailfrom,$DT_fromname,$Itemid,$my;

	global $mainframe;

	require_once("../components/com_dtregister/config.dtregister.php");

	$database = &JFactory::getDBO();

	$eventId = $_REQUEST['event_id'];
  
	if( $_REQUEST['groupMemberId']==0){
	   
	   $newmem = new Member();
	   
	   $newmem->groupUserId = $_REQUEST['groupUserId'] ;
	   $newmem->add((object)$_POST);
	   
	    $mainframe->redirect("index.php?option=com_dtregister&task=showmembers&gid=".$newmem->groupUserId."&event_id=".$eventId."",'Record Saved.');
	   
	}
	
  $fld = new Custom_field();
			$fields=array() ;
			
            $fld->getAllFields($eventId,'M',true,0,$fields) ;
			
			$rows = $fields ;
			
	$arrFields = array (

			1 	=> array('firstname', JText::_('DT_FIRSTNAME'), 'm_s_firstname', 'm_r_firstname',JText::_('DT_ENTER_FNAME')),

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

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

			4 	=> array('address', JText::_('DT_ADDRESS'), 'm_s_address', 'm_r_address',JText::_('DT_ENTER_ADDRESS')),

			5 	=> array('city', JText::_('DT_CITY'), 'm_s_city', 'm_r_city',JText::_('DT_ENTER_CITY')),

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

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

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

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

			10 	=> array('cemail', JText::_('DT_CONFIRM_EMAIL'), 'm_s_email', 'm_r_email',JText::_('DT_ENTER_EMAIL')),

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

		);

	$arrFieldIds=array();

	for($i=0,$n=count($rows);$i<$n;$i++){
      
		$arrFieldIds[]=$rows[$i]->id;

		$requires[$rows[$i]->id] = $rows[$i]->required;

	}

	if(count($arrFieldIds))	{

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

		$database->setQuery($sql);

		if($database->getErrorMsg()){

			echo $database->getErrorMsg();

		}

		$rowCustoms=$database->loadObjectList();

		

	} else {

		$rowCustoms=null;

	}

	$arrPostVals = array();

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

		if(isset($_POST[$value[0]])){

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

		    array_push_associative($arrPostVals,$arr);

		}

	}

	unset($arrPostVals['cemail']);

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

		if(isset($_POST[$value->name])){

			if(is_array($_POST[$value->name])){

				$arr = array($value->name=>implode('|',$_POST[$value->name]));

			}else{

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

			}

			array_push_associative($arrPostVals,$arr);

		}

	}

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

		$query[] = $key."="."'".$value."'";

	}

	$query = 'update #__dtregister_group_member set '.implode(',',$query).' where groupMemberId='.$_REQUEST['groupMemberId'];

	$database->setQuery($query);

	$database->query();


    $mainframe->redirect("index.php?option=com_dtregister&task=showmembers&gid=".$_REQUEST['gid']."&event_id=".$_REQUEST['event_id']."",'Record Saved.');

}

function addgroupmember(){
  include( JPATH_SITE.'/administrator/components/com_dtregister/view/member/add.php');
}

function editgroupmember($option,$cid){
include( JPATH_SITE.'/administrator/components/com_dtregister/view/member/edit.php');

}

function deleteDiscountcode($option){

	global $mainframe;

	foreach($_REQUEST['cid'] as $value){

		$dt_code =  new DiscountCode($value);

		$dt_code->delete();

	}

	$url = "index.php?option=com_dtregister&task=discount_codes";

	$mainframe->redirect($url,'Discount Code Deleted.');

}

function publishDiscountCode($publish){

	global $mainframe;

	$dt_code =  new DiscountCode($_REQUEST['cid'][0]);

	$dt_code->publish = $publish;

	$dt_code->save();

	$url = "index.php?option=com_dtregister&task=discount_codes";

	$mainframe->redirect($url,'Discount Code Updated.');

}

function saveDiscountCode($option){

	global $mainframe;

	$discount_code = new DiscountCode();

	if($_REQUEST['name']!=''){

		if(!$discount_code->check_space($_REQUEST['name'])){

			?>

            var form=document.adminForm;

			var fieldName=form.name;

            var re = new RegExp("[ ]", "g");

			fieldName.value= fieldName.value.replace(re,"_");

		  alert("<?php echo $discount_code->error ;?>");

			<?php

			exit;

		}

	}

	if(!$discount_code->validate_name($_REQUEST['name'])){

		?>

		  alert("<?php echo $discount_code->error ;?>");

		<?php

		exit;

	}

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

		$discount_code->id = $_REQUEST['id'];

		if(!$discount_code->validate_code($_REQUEST['code'])){

			$url = "index.php?option=com_dtregister&task=new_discount_code";

			?>

			 alert('<?php echo DT_ALERT_CODE_EXISTS ?>');

            <?php

			exit;

		}

	}else{

		if(!$discount_code->validate_code($_REQUEST['code'])){

			$url = "index.php?option=com_dtregister&task=new_discount_code";

			?>

			 alert('<?php echo DT_ALERT_CODE_EXISTS ?>');

            <?php

			exit;

		}

	}

	if(strtotime($_REQUEST['start']) > strtotime($_REQUEST['end'])){

		$url = "index.php?option=com_dtregister";

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

			$discount_code->id = $_REQUEST['id'];

			$url .= "&task=edit_discount_code&id=".$_REQUEST['id'];

		}else{

			$url .="&task=new_discount_code";

		}

		?>

               alert('Date is not valid');

            <?php

			exit;

	}else{

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

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

				$form_id = "updateDiscountCode";

			}else{

				$form_id = "newDiscountCode";

			}

		 ?>

       		document.adminForm.task.value = '<?php echo $_REQUEST['task'];?>';

       		DTjQuery('#<?php echo $form_id;?>').submit();

    	<?php

			exit ;

		}

		$discount_code->set($_REQUEST);

		$discount_code->save();

		$url = "index.php?option=com_dtregister&task=discount_codes";

		 $mainframe->redirect($url, JText::_('DT_ALERT_DISCOUNT_CREATED'));

	}

}

function listdiscountcodes($option ){

	$discount_code = new DiscountCode();

	$rows = $discount_code->getcodes();

	HTML_groups::listdiscountcodes($option,$rows);

}

function newDiscountCode($option ){

	HTML_groups::newDiscountCode($option);

}

function editDiscountCode($option ){

	$dt_code =  new DiscountCode($_REQUEST['id']);

	HTML_groups::editDiscountCode($option,$dt_code);

}

function exportFieldSettings($option){

	global $database,$mosConfig_live_site,$mosConfig_absolute_path,$DT_mailfrom,$DT_fromname,$Itemid,$my;

	$database = &JFactory::getDBO();

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

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

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

			5 	=> array('address', JText::_('DT_ADDRESS'), 'm_s_address', 'm_r_address',JText::_('DT_ENTER_ADDRESS')),
			
			6 	=> array('address2', JText::_('DT_ADDRESS2'), 'm_s_address2', 'm_r_address2',JText::_('DT_ENTER_ADDRESS2')),

			7 	=> array('city', JText::_('DT_CITY'), 'm_s_city', 'm_r_city',JText::_('DT_ENTER_CITY')),

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

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

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

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

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

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

	$sql="Select *  From #__dtregister_fields where type <> 6";

	$database->setQuery($sql);

	$rows=$database->loadObjectList();

	$fields['custom_fields'] = $rows;

	$fields['fields'] = $mem_arrFields;

	 $sql="Select * From #__dtregister_export_fields";

	$database->setQuery($sql);

	$fieldsetting=$database->loadObjectList();

	$fields['group_fields'] =explode(",",$fieldsetting[0]->group_export_fields);

	$fields['individual_fields'] =explode(",",$fieldsetting[0]->individual_export_fields);

	$fields['general_export_fields'] =explode(",",$fieldsetting[0]->general_export_fields);

	HTML_groups::exportFieldSettings($option,$fields);

}

function saveEventExportSetting($option){

	global $Itemid,$my;

	$mosConfig_live_site = JURI::base( true );

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

	if(!isset($_POST['events'])){

		$_POST['events'] = array();

	}

	if(!isset($_POST['export_events'])){

		$_POST['export_events'] = array();

	}

	$database = &JFactory::getDBO();

	$export_not = array_diff($_POST['events'],$_POST['export_events']);

	 $sql="update #__dtregister_group_event set export=1 where eventId in(".implode(',',$_POST['export_events']).") ";

	$database->setQuery($sql);

	$database->query();

	 $sql="update #__dtregister_group_event set export=0 where eventId in(".implode(',',$export_not).") ";

	$database->setQuery($sql);

	$database->query();

	exportFieldSettings($option);

}

function saveFieldExportSetting($option){

	global $mosConfig_absolute_path,$Itemid,$my,$database;

    if(empty($_POST['individual_custom_export_fields'])){

		$_POST['individual_custom_export_fields'] = array();

	}

	if(empty($_POST['group_custom_export_fields'])){

		$_POST['group_custom_export_fields'] = array();

	}

	if(empty($_POST['group_export_fields'])){

		$_POST['group_export_fields'] = array();

	}

	if(empty($_POST['general_export_fields'])){

		$_POST['general_export_fields'] = array();

	}

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	include( '../components/com_dtregister'.DS.'config.dtregister.php');

	$database = &JFactory::getDBO();

	$individual_custom_export_not = array_diff($_POST['individual_custom_fields'],$_POST['individual_custom_export_fields']);

	$sql="update #__dtregister_fields set export_individual=0 where id in(".implode(',',$individual_custom_export_not).") ";

	$database->setQuery($sql);

	$database->query();

	$sql="update #__dtregister_fields set export_individual=1 where id in(".implode(',',$_POST['individual_custom_export_fields']).") ";

	$database->setQuery($sql);

	$database->query();

	$group_custom_export_not = array_diff($_POST['group_custom_fields'],$_POST['group_custom_export_fields']);

	$sql="update #__dtregister_fields set export_group=0 where id in(".implode(',',$group_custom_export_not).") ";

	$database->setQuery($sql);

	$database->query();

	$sql="update #__dtregister_fields set export_group=1 where id in(".implode(',',$_POST['group_custom_export_fields']).") ";

	$database->setQuery($sql);

	$database->query();

	//$individual_export_not = array_diff($_POST['individual_fields'],$_POST['individual_export_fields']);

	  $sql =  'select count(*) from #__dtregister_export_fields';

	  $database->setQuery($sql);

	  //$database->query();

	  $data =$database->loadresult();

	  if($data > 0){

	  		 $sql="update #__dtregister_export_fields set group_export_fields='".implode(',',$_POST['group_export_fields'])."' , individual_export_fields='".implode(',',$_POST['individual_export_fields'])."' , general_export_fields='".implode(',',$_POST['general_export_fields'])."' ";

	  }else{

	  			 $sql="insert #__dtregister_export_fields set group_export_fields='".implode(',',$_POST['group_export_fields'])."' , individual_export_fields='".implode(',',$_POST['individual_export_fields'])."' , general_export_fields='".implode(',',$_POST['general_export_fields'])."' ";

	  }

	$database->setQuery($sql);

	$database->query();

	//$group_export_not = array_diff($_POST['group_fields'],$_POST['group_export_fields']);

	doexportCSV($option);

}

function payLaterPaid($option,$cid,$publish)

{

	global $Itemid,$mainframe;

//	$mosConfig_fromname = $mainframe->getCfg('fromname');

	//$mosConfig_mailfrom = $mainframe->getCfg('mailfrom');

	$mosConfig_live_site = JURI::base( true );

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

	$database = &JFactory::getDBO();

	JArrayHelper::toInteger( $cid );

    $dt_user = new DT_User($cid[0]);
	
	if($publish==1){
	  $due_payment = 0;   
	}else{
	   $due_payment = $dt_user->get_amount();
	}
	//$dt_user->save_field('due_payment',$due_payment);

	$cids = ' userId=' . implode( ' OR  userId=', $cid );

	$query = "UPDATE #__dtregister_user"

	. "\n SET pay_later_paid = " . (int) $publish

	. "\n WHERE ( $cids )"

	;
    $dt_user->pay_later_paid =  (int) $publish ;
	if($paid_status_change_msg_send)
	paidStatusNotification($dt_user);
	
	$database->setQuery( $query );

	if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

		exit();

	}

	 $_REQUEST['task'] = 'listregistrations';
	
    $get_str = http_build_query($_REQUEST);

         $mainframe->redirect("index2.php?".$get_str);

	$mainframe->redirect("index2.php?option=com_dtregister&task=listregistrations&order=".Jrequest::getVar( 'order' )."&dir=".Jrequest::getVar( 'dir' ));

}

function paidStatusNotification($dt_user){
   
   global $Itemid,$mainframe;
   include( JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
   $status =  array(JText::_('DT_ACTIVE'),JText::_('DT_CANCELLED'),JText::_('DT_PENDING'));
   $paid_status = array(JText::_('NO'),JText::_('YES'));
    $dt_user->event = new Event($dt_user->eventId);
  $message = thanks_email_tags($dt_user,$paid_status_change_msg);
  $status =  array(JText::_('DT_ACTIVE'),JText::_('DT_CANCELLED'),JText::_('DT_PENDING'));
  $paid_status = array(0=>JText::_('DT_NOT_PAID'),1=>JText::_('DT_PAID'));
  $subpaidstatusemail = str_replace('[EVENT_NAME]',$dt_user->event->summary,$subpaidstatusemail);
  
  $subpaidstatusemail = str_replace('[EVENT_DATE]',get_date($dt_user->event->dtstart,$dt_user->event->dtend),$subpaidstatusemail);
  $subpaidstatusemail = str_replace('[STATUS]',$status[$dt_user->cancel],$subpaidstatusemail);
  $subpaidstatusemail = str_replace('[PAID_STATUS]',$paid_status[$dt_user->pay_later_paid],$subpaidstatusemail);
  
  $conf = &JFactory::getConfig();
   if($DT_mailfrom == ""){
     $DT_mailfrom = $conf->_registry['config']['data']->mailfrom;
  }
  if($DT_fromname==""){
     $DT_fromname =$conf->_registry['config']['data']->fromname;
  }
 // $mosConfig_mailfrom = $conf->_registry['config']['data']->mailfrom;
 //$mosConfig_fromname =$conf->_registry['config']['data']->fromname;
  JUTility::sendMail( $DT_mailfrom, $DT_fromname,$dt_user->userEmail,$subpaidstatusemail,$message,1,null,null);
   
}

function statusNotification($dt_user){
   
   global $Itemid,$mainframe;
   include( JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
   $status =  array(JText::_('DT_ACTIVE'),JText::_('DT_CANCELLED'),JText::_('DT_PENDING'));
   $paid_status = array(JText::_('NO'),JText::_('YES'));
    $dt_user->event = new Event($dt_user->eventId);
  $message = thanks_email_tags($dt_user,$status_change_msg);
  $status =  array(JText::_('DT_ACTIVE'),JText::_('DT_CANCELLED'),JText::_('DT_PENDING'));
  $paid_status = array(0=>JText::_('DT_NOT_PAID'),1=>JText::_('DT_PAID'));
  $subchangestatusemail = str_replace('[EVENT_NAME]',$dt_user->event->summary,$subchangestatusemail);
  
  $subchangestatusemail = str_replace('[EVENT_DATE]',get_date($dt_user->event->dtstart,$dt_user->event->dtend),$subchangestatusemail);
  $subchangestatusemail = str_replace('[STATUS]',$status[$dt_user->cancel],$subchangestatusemail);
  $subchangestatusemail = str_replace('[PAID_STATUS]',$paid_status[$dt_user->pay_later_paid],$subchangestatusemail);
 
  $conf = &JFactory::getConfig();
   if($DT_mailfrom == ""){
     $DT_mailfrom = $conf->_registry['config']['data']->mailfrom;
  }
  if($DT_fromname==""){
     $DT_fromname =$conf->_registry['config']['data']->fromname;
  }
//  $mosConfig_mailfrom = $conf->_registry['config']['data']->mailfrom;
//  $mosConfig_fromname =$conf->_registry['config']['data']->fromname;
  
  JUTility::sendMail( $DT_mailfrom, $DT_fromname,$dt_user->userEmail,$subchangestatusemail,$message,1,null,null);
   
}

function cancelRegistration($option)

{

	global $mainframe;

	$mainframe->redirect("index2.php?option=com_dtregister&task=listregistrations");

}

function saveGroupRegistration($option)

{

	global $DT_fromname,$DT_mailfrom, $mainframe;

	$database = &JFactory::getDBO();

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

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

	 $user = &JFACTORY::getUser();

	 $userId = JRequest::getInt( 'user_id', 0, 'post' );

	 $eventId = JRequest::getInt( 'event_id', 0, 'post' );

	 $title = Jrequest::getVar( 'title' );
	 
	 $fname = Jrequest::getVar( 'fname' );

	 $lname = Jrequest::getVar( 'lname' );

	 $address = Jrequest::getVar( 'address' );
	 
	 $address2 = Jrequest::getVar( 'address2' );

	 $city = Jrequest::getVar( 'city' );

	 $state = Jrequest::getVar( 'state' );

	 $zip = Jrequest::getVar( 'zip' );

	 $country = Jrequest::getVar( 'country' );

	 $phone = Jrequest::getVar( 'phone' );

	 $email = Jrequest::getVar( 'email' );

	 $org = Jrequest::getVar( 'org' );

	 $paymentType = Jrequest::getVar( 'payment_type');

	 //Other information which is really need

	 $memtot = Jrequest::getInt( 'memtot', 0, 'post' );

	 $amountCharged = Jrequest::getVar( 'amountCharged' );
	 
	 $paid_amount = Jrequest::getVar( 'paid_amount', 0, 'post' );

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

	 $database->setQuery($sql);

	 $eventName=$database->loadResult();

	//Update custom fields cost

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

	 $database->setQuery($sql);

	 $rows=$database->loadObjectList();
	 $fld = new Custom_field();
			$fields=array() ;
			
     $fld->getAllFields($eventId,'M',true,0,$fields) ;
	 
	 $rows = $fields ;
	 
	$arrFieldIds=array();

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

	{

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

	}

	if(count($arrFieldIds))

	{

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

		$database->setQuery($sql);

		if($database->getErrorMsg())

			echo $database->getErrorMsg();

		$rowCustoms=$database->loadObjectList();

	}

	else

	{

		$rowCustoms=null;

	}
 
	//Get members data passed as hidden variables

	//End of get hidden variables passed by
    
	if($m_s_title)

	{

		$arrTitle=Jrequest::getVar('arr_title', array(), 'post', 'array');

	}
	
	if($m_s_firstname)

	{

		$arrFirstName=Jrequest::getVar('arr_firstname', array(), 'post', 'array');

	}

	if($m_s_lastname)

	{

		$arrLastName=Jrequest::getVar('arr_lastname', array(), 'post', 'array');

	}

	if($m_s_organization)

	{

		$arrOrganization=Jrequest::getVar('arr_organization', array(), 'post', 'array');

	}

	if($m_s_address)

	{

		$arrAddress=Jrequest::getVar('arr_address', array(), 'post', 'array');

	}
	
	if($m_s_address2)

	{

		$arrAddress2=Jrequest::getVar('arr_address2', array(), 'post', 'array');

	}

	if($m_s_city)

	{

		$arrCity=Jrequest::getVar('arr_city', array(), 'post', 'array');

	}

	if($m_s_state)

	{

		$arrState=Jrequest::getVar('arr_state', array(), 'post', 'array');

	}

	if($m_s_zip)

	{

		$arrZip=Jrequest::getVar('arr_zip', array(), 'post', 'array');

	}

	if($m_s_country)

	{

		$arrCountry=Jrequest::getVar('arr_country', array(), 'post', 'array');

	}

	if($m_s_email)

	{

		$arrEmail=Jrequest::getVar('arr_email', array(), 'post', 'array');

	}

	if($m_s_phone)

	{

		$arrPhone=Jrequest::getVar('arr_phone', array(), 'post', 'array');

	}

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

	{

		$rowCustom=$rowCustoms[$i];

		$name=$rowCustom->name;

		$arrName="arr_$name";

		if(isset($_POST[$arrName]))

		{

			$arrName="arr_$name";

			$$arrName=Jrequest::getVar($arrName, array(), 'post', 'array');

		}

	}

	$database = &JFactory::getDBO();

	$pay_later_paid=Jrequest::getVar('pay_later_paid');

	if(($paymentType !='Authorize.net') && ($paymentType !='Authorize.net') && ($paymentType !='Authorize.net'))

	{

		//Change it to pay later

		switch ($paymentType)

		{

			case "Mail-in Payment":

				$payLaterOption=2;

				break;

			case "Phone Payment":

				$payLaterOption=3;

				break;

			case "At The Door":

				$payLaterOption=1;

				break;

			default:

				$payLaterOption=1;

				break;

		}

		//$paymentType="Pay Later";

	}
    
	

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

	  $dt_reg = new DT_User(null,$eventId);
     $confirmNum = $dt_reg->generateconfirmNum();
	 $dt_reg->calculate_fee( $memtot,$_POST['user_id'] ,Jrequest::getVar('discount_code'));

///	  echo "<>"

      $dt_reg->event->get_custom_fields_fee($memtot);

	 $dt_reg->event->member_discount;
      $dt_reg->discount_code_amount = isset($dt_reg->discount_code_amount)?$dt_reg->discount_code_amount:0;
	  $amountCharged += $dt_reg->event->get_custom_fields_fee($memtot)- $dt_reg->discount_code_amount - $dt_reg->event->member_discount;
   
	 $rowCustoms = $dt_reg->event->get_billing_custom_field();

	 $data=Jrequest::get('post');

	 $tfields = array();
       $fld = new Custom_field();
			$fields=array() ;
			
     $fld->getAllFields($eventId,'B',true,0,$tfields) ;
	 
	 $rowCustoms = $tfields ;
	 $fields = array();
	 foreach($rowCustoms as $key=>$rowCustom){

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

			$fields[] = $rowCustom->name;

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

				$values[] = $database->Quote(implode('|',$data[$rowCustom->name]));
                
				
			}else{

				$values[] = $database->Quote($data[$rowCustom->name]);
				

			}

	   }

	 }

	 if(count($fields)>0){

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

	 	$custom_values = ", ".implode(",",$values)." ";
	 }else{

	 	$custom_fields = '';

		$custom_values = '';

	 }

$sql="INSERT into #__dtregister_user(eventid, usertype, userTitle, userfirstname, userlastname, userorganization, useraddress,useraddress2 , usercity, userstate, userzip, userphone, useremail,register_date,userCountry,payment_type,user_id,pay_later_option,pay_later_paid,confirmNum,discount_code_id ".$custom_fields." , paid_amount) values($eventId,'G',".$database->Quote($title)." ,".$database->Quote($fname).",".$database->Quote($lname).", ".$database->Quote($org).",".$database->Quote($address).", ".$database->Quote($address2).",'$city','$state','$zip','$phone','$email',now(),'$country','$paymentType','$user->id','$payLaterOption','$pay_later_paid','$confirmNum',".$dt_reg->discount_id." ".$custom_values." , '$paid_amount')";

	$database->setQuery($sql);

	$database->query();

	$uid= $database->insertid();
	
	if($barcode_enable){
      $barcode = new DTbarcode($confirmNum,$confirmNum);
      $barcode->preview();
	}
	////////////////////////////////////////////////////////////////////////////////////////////////////////////

	$sql="insert into #__dtregister_group(useid) values($uid)";

	$database->setQuery($sql);

	$database->query();

	$gid=$database->insertid();

	//Insert members

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

		$arrMemberFields=array();

		$arrMemberValues=array();

		//Check and get member data here

		$arrMemberFields[]='groupUserId';

		$arrMemberValues[]=$gid;
        
		if($m_s_title)

		{

			$arrMemberFields[]='title';

			$arrMemberValues[]=$arrTitle[$i];

		}
		
		if($m_s_firstname)

		{

			$arrMemberFields[]='firstname';

			$arrMemberValues[]=$arrFirstName[$i];

		}

		if($m_s_lastname)

		{

			$arrMemberFields[]='lastname';

			$arrMemberValues[]=$arrLastName[$i];

		}

		if($m_s_organization)

		{

			$arrMemberFields[]='organization';

			$arrMemberValues[]=$arrOrganization[$i];

		}

		if($m_s_address)

		{

			$arrMemberFields[]='address';

			$arrMemberValues[]=$arrAddress[$i];

		}
		
		if($m_s_address2)

		{

			$arrMemberFields[]='address2';

			$arrMemberValues[]=$arrAddress2[$i];

		}

		if($m_s_city)

		{

			$arrMemberFields[]='city';

			$arrMemberValues[]=$arrCity[$i];

		}

		if($m_s_state)

		{

			$arrMemberFields[]='state';

			$arrMemberValues[]=$arrState[$i];

		}

		if($m_s_zip)

		{

			$arrMemberFields[]='zip';

			$arrMemberValues[]=$arrZip[$i];

		}

		if($m_s_country)

		{

			$arrMemberFields[]='country';

			$arrMemberValues[]=$arrCountry[$i];

		}

		if($m_s_email)

		{

			$arrMemberFields[]='email';

			$arrMemberValues[]=$arrEmail[$i];

		}

		if($m_s_phone)

		{

			$arrMemberFields[]='phone';

			$arrMemberValues[]=$arrPhone[$i];

		}
		 $fld = new Custom_field();
			$fields=array() ;
			
            $fld->getAllFields($eventId,'M',true,0,$fields) ;
			
			$rowCustoms = $fields ;
        
		if(isset($rowCustoms))

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

		{

			$rowCustom=$rowCustoms[$j];

			$name=$rowCustom->name;

			$arrName="arr_$name";

			if(isset($_POST[$arrName]))

			{

				$arrName="arr_$name";

				$datas=JRequest::getVar( $arrName, array(), 'post', 'array' );

				$arrMemberFields[]=$name;

				$arrMemberValues[]=$datas[$i];

			}

		}

		//Insert data into the tables

		;

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

	}
        $dt_event =  new Event($eventId);
	 $amountCharged += $dt_event->getTaxAmount($amountCharged);
	 if($paid_amount<$amountCharged){
	    $cancel = $partial_default_status ;
	 }else{
	     $cancel = $paid_default_status ;
	 }
	 
	 if(in_array($paymentType,array('At_door','Mail','Phone'))){
	    $cancel = $paylater_default_status ;
	 }
	  $sql = "update #__dtregister_user set cancel=".$cancel."  where userId=".$uid;

		 $database->setQuery($sql);

			$database->query();

		$sql="insert into #__dtregister_group_amount(groupId,numberOfPerson,amount)values('$gid','$memtot','$amountCharged')";

		$database->setQuery($sql);

		$database->query();

		//echo $thanksmsg;

		$subthanksemail = sprintf($subthanksemail,$eventName);

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

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

		$adminmsg="<pre>";

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

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

		$adminmsg.="<table>";

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

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

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

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

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

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

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

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

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

		$adminmsg.="<tr><td colspan=2>".JText::_( 'DT_ADMIN_GROUP_DETAILS' ).":</td></tr>";

		$sql="Select * From #__dtregister_group_member Where groupUserId=$gid";

		$database->setQuery($sql);

		$rowMembers=$database->loadObjectList();

		$adminmsg.="<tr><td colspan=2><table>";
       
		for($i=0;$n<count($rowMembers)&& $i<$n;$i++)

		{

			$rowMember=$rowMembers[$i];

			$adminmsg.="<tr>";

			if($m_s_firstname)

			{

				$adminmsg.="<td>".$rowMember->firstname."</td>";

			}

			if($m_s_lastname)

			{

				$adminmsg.="<td>".$rowMember->lastname."</td>";

			}

			if($m_s_organization)

			{

				$adminmsg.="<td>".$rowMember->organization."</td>";

			}

			if($m_s_address)

			{

				$adminmsg.="<td>".$rowMember->address."</td>";

			}

			if($m_s_city)

			{

				$adminmsg.="<td>".$rowMember->city."</td>";

			}

			if($m_s_state)

			{

				$adminmsg.="<td>".$rowMember->state."</td>";

			}

			if($m_s_zip)

			{

				$adminmsg.="<td>".$rowMember->zip."</td>";

			}

			if($m_s_country)

			{

				$adminmsg.="<td>".$rowMember->country."</td>";

			}

			if($m_s_email)

			{

				$adminmsg.="<td>".$rowMember->email."</td>";

			}

			if($m_s_phone)

			{

				$adminmsg.="<td>".$rowMember->phone."</td>";

			}

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

			{

				$rowCustom=$rowCustoms[$j];

				$name=$rowCustom->name;

				if(isset($_POST[$name]))

				{

					$adminmsg.="<td>".$rowMember->$name."</td>";

				}

			}

			$adminmsg.="</tr>";

		}
      
	$adminmsg.="</table></td></tr></table></pre>";

	//Get the admin email now

	$database = &JFactory::getDBO();

   if(isset($_POST['sendemail'])){
	    registration_email_frontend($uid);
	}
	  
	  //JUTility::sendMail( $mosConfig_mailfrom, $mosConfig_fromname,$adminemail,$subadmin,$adminmsg,1);

    //JUTility::sendMail( $mosConfig_mailfrom, $mosConfig_fromname,$email,$subthanksemail,$thanksemail,1);

   $mainframe->redirect("index2.php?option=com_dtregister&task=listregistrations","Registration record saved");

}

function newGroupRegistration($option)

{

	$database = &JFactory::getDBO();

	$eventId=Jrequest::getInt( 'event_id', 0, 'post' );

	$sql="Select * From #__jevents_vevdetail where evdet_id =$eventId";

	$database->setQuery($sql);

	$rowEvent = $database->loadObject();

	HTML_groups::newGroupRegistration($option,$eventId,$rowEvent);

}

function membersDetail($option)

{

	global $mosConfig_dbprefix;

	$mosConfig_live_site = JURI::base( true );

	$database = &JFactory::getDBO();

	$user = &JFactory::getUser();

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

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

    $eventId=Jrequest::getInt( 'event_id', 0, 'post' );
    $dt_event =  new Event($eventId);
  	$memtot = Jrequest::getInt( 'memtot', 0, 'post' );

	 $query = "select *,if(NOW()>latefeedate,'y','n') as late from #__dtregister_group_event WHERE

	 eventid=$eventId ORDER BY memberTotal ASC";

	 $database->setQuery($query);

	 $res = $database->loadObjectList();

	 $amountCharged = 0;

	 $latefee =0;

	 //Here will be the discount applied

	 $userId=$user->id;

	 foreach($res as $r){

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

 		$amountCharged = $r->regGroupPerRate * $memtot;

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

		{

			$latefee = $r->latefee*$memtot;

		}

	 }

	 else

	 break;

	 }
  $amountCharged =  $dt_event->get_fee($memtot,0);
?>

    <link href="<?php echo $mosConfig_live_site;?>/components/com_dtregister/assets/css/main.css" rel="stylesheet" type="text/css">

    <script language="javascript" src="<?php echo $mosConfig_live_site?>/includes/js/joomla.javascript.js"></script>

    <script language="javascript">

    	function submitbutton(pressbutton)

    	{

           	if(pressbutton=="cancel_registration")

    		{

    			submitform(pressbutton);

    		}

    		else

    		{

    			var form=document.adminForm;

    			var currentMember=form.current_member.value;

    			currentMember++;

    			form.current_member.value=currentMember;

    			submitform(pressbutton);

    		}

    	}

    </script>

<?php

	$database = &JFactory::getDBO();
   
    $fld = new Custom_field();
    $fields=array() ;
	$fld->getAllFields($eventId,'M',true,0,$fields) ;
	$rowCustoms = $fields ;
	
	
	$currentMember=Jrequest::getInt( 'current_member', 1, 'post' );

	//Get member data which is passed as hidden variable
    
	if($m_s_title)

	{

		$arrTitle=JRequest::getVar( 'arr_title', array(), 'post', 'array' );

	}
	
	if($m_s_firstname)

	{

		$arrFirstName=JRequest::getVar( 'arr_firstname', array(), 'post', 'array' );

	}

	if($m_s_lastname)

	{

		$arrLastName=JRequest::getVar( 'arr_lastname', array(), 'post', 'array' );

	}

	if($m_s_organization)

	{

		$arrOrganization=JRequest::getVar( 'arr_organization', array(), 'post', 'array' );

	}

	if($m_s_address)

	{

		$arrAddress=JRequest::getVar( 'arr_address', array(), 'post', 'array' );

	}
    
	if($m_s_address2)

	{

		$arrAddress2=JRequest::getVar( 'arr_address2', array(), 'post', 'array' );

	}

	if($m_s_city)

	{

		$arrCity=JRequest::getVar( 'arr_city', array(), 'post', 'array' );

	}

	if($m_s_state)

	{

		$arrState=JRequest::getVar( 'arr_state', array(), 'post', 'array' );

	}

	if($m_s_country)

	{

		$arrCountry=JRequest::getVar( 'arr_country', array(), 'post', 'array' );

	}

	if($m_s_zip)

	{

		$arrZip=JRequest::getVar( 'arr_zip', array(), 'post', 'array' );

	}

	if($m_s_email)

	{

		$arrEmail=JRequest::getVar( 'arr_email', array(), 'post', 'array' );

	}

	if($m_s_phone)

	{

		$arrPhone=JRequest::getVar( 'arr_phone', array(), 'post', 'array' );

	}

	if(isset($rowCustoms))

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

	{

		$rowCustom=$rowCustoms[$i];

		$name=$rowCustom->name;

		$arrName="arr_$name";

		if(isset($_POST[$arrName]))

		{

			$arrName="arr_$name";

			$$arrName=JRequest::getVar( $arrName, array(), 'post', 'array' );

		}elseif(isset($_POST['current_member'])){
		    $$arrName = "" ;	
		}

	}
   
	if($currentMember>1)

	{

		//Get entered data and store it into an array
         
		if($m_s_title)

		{

			$title=JRequest::getVar( 'title' );

			$arrTitle[]=$title;

		}
		 
		if($m_s_firstname)

		{

			$firstName=JRequest::getVar( 'firstname' );

			$arrFirstName[]=$firstName;

		}

		if($m_s_lastname)

		{

			$lastName=JRequest::getVar( 'lastname' );

			$arrLastName[]=$lastName;

		}

		if($m_s_organization)

		{

			$organization=JRequest::getVar( 'organization' );

			$arrOrganization[]=$organization;

		}

		if($m_s_address)

		{

			$address=JRequest::getVar( 'address' );

			$arrAddress[]=$address;

		}
		
		if($m_s_address2)

		{

			$address2=JRequest::getVar( 'address2' );

			$arrAddress2[]=$address2;

		}

		if($m_s_city)

		{

			$city=JRequest::getVar( 'city' );

			$arrCity[]=$city;

		}

		if($m_s_state)

		{

			$state=JRequest::getVar( 'state' );

			$arrState[]=$state;

		}

		if($m_s_zip)

		{

			$zip=JRequest::getVar( 'zip' );

			$arrZip[]=$zip;

		}

		if($m_s_country)

		{

			$country=JRequest::getVar( 'country' );

			$arrCountry[]=$country;

		}

		if($m_s_email)

		{

			$email=JRequest::getVar( 'email' );

			$arrEmail[]=$email;

		}

		if($m_s_phone)

		{

			$phone=JRequest::getVar( 'phone' );

			$arrPhone[]=$phone;

		}
        if(isset($rowCustoms) && isset($_POST['current_member']))
		for($i=0,$n=count($rowCustoms);$i<$n;$i++)

		{

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$type=$rowCustom->type;

			if(isset($_POST[$name]) || isset($$arrName))

			{

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

				if($type==3)

				{

					$value[0]=implode('|',$value);

				}

				$arrName="arr_$name";

				if(!isset($$arrName) || !is_array($$arrName)){

					$$arrName = array();

				}

				array_push($$arrName,$value);

			}

		}

	}

?>
 <script src="<?php echo Juri::root();  ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>
  <script src="<?php echo Juri::root();  ?>/components/com_dtregister/assets/js/textareaCounter.js" type="text/javascript"></script>
<form name="adminForm" action="index2.php" method="post" name="adminForm" id="adminForm">

<table class="authorizenetformtable">

<tr><td><?php echo $topmsg; ?></td></tr>

<tr>

	<td>

		<div align="center">

			<?php echo JText::_( 'DT_REGISTRATION_FEE' );?>: <?php echo $memtot?> x <?php echo numberFormat($amountCharged/$memtot,2);?><?php if ($latefee>0){?> + late fee <?php echo numberFormat($latefee,2)?><?php } ?> = <?php if(isset($currency_symbol)) {echo $currency_symbol;} else {echo  '';}?><?php echo numberFormat($amountCharged,2);?>

			<?php if ($latefee>0){?>+<?php echo numberFormat($latefee,2);?><?php } ?>

		</div>

	</td>

</tr>

</table>

<table align='center' width='100%' border='0' cellpadding='2' cellspacing='2' class="adminform">
<tbody>
		<!-- Here will we the general information-->

    	<tr >

		<td colspan="3" align="left" ><strong>Member <?php echo $currentMember; ?> Information</strong></td>

		</tr>

		<tr><td colspan="3">( <span class="required">*</span> = <?php echo JText::_( 'DT_REQUIRED_FIELD' );?> )</td></tr>
         <?php
           if($m_s_title){
		       
			   $titles = explode("|",$titleoptions);
			   $temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

			  foreach($titles as $title){
	
				$temp[] = JHTML::_('select.option', $title, $title);
			   
		      }
			  $titles = $temp;
			  ?>

				<tr>

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

					<td width="68%" align="left" ><?php echo   JHTML::_('select.genericlist',$temp,"title", 'class="inputbox" size="1"', 'value', 'text');?></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}
			  
		 ?>  
           
		<?php

			if($m_s_firstname)

			{

			?>

				<tr>

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

					<td width="68%" align="left" ><input type="text" name="firstname" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

			if($m_s_lastname)

			{

			?>

				<tr>

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

					<td width="68%" align="left" ><input type="text" name="lastname" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				 </tr>

			<?php

			}

			if($m_s_organization)

			{

			?>

				<tr><td width="30%" ><?php echo JText::_( 'DT_ORGANIZATION' );?>:

				<?php

					if(isset($p_organization)&&$p_organization)

					{

					?>

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

					<?php

					}

				?>

				</td>

				<td width="68%" align="left" ><input type="text" name="organization" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

			if($m_s_address)

			{

			?>

				<tr>

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

				<td width="68%" align="left" ><input type="text" name="address" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}
            ?>
            <?php
			if($m_s_address2){
			?>
			   <tr>

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

				<td width="68%" align="left" ><input type="text" name="address2" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>
			<?php
			}
			
			?>
            <?php
			if($m_s_city)

			{

			?>

				<tr>

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

				<td width="68%" align="left" ><input type="text" name="city" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

			if($m_s_state)

			{

			?>

				<tr>

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

				<td width="68%" align="left" ><input type="text" name="state" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

			if($m_s_zip)

			{

			?>

				<tr>

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

				<td width="68%" align="left" ><input type="text" name="zip" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

			if($m_s_country)

			{

				 require_once(JPATH_SITE.'/components/com_dtregister/country.htm');

			}

			if($m_s_email)

			{

			?>

				<tr>

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

					<td width="68%" align="left" ><input type="text" name="email" value="" class="inputbox" /></td>
 <td width="2%" >&nbsp;</td>
				</tr>

				<tr>

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

				<td width="68%" align="left" ><input type="text" name="cemail" value="" class="inputbox" /></td>
                <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

			if($m_s_phone)

			{

			?>

				<tr>

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

				<?php

					if(isset($p_phone))

					{

					?>

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

					<?php

					}

				?>

				</td>

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

				</td>
                 <td width="2%" >&nbsp;</td>
				</tr>

			<?php

			}

		?>

		<!-- Here will be custom fields output code-->

		<?php

				  	//Get Custom Fields

                    echo $dt_event->field_html('G',null,true,'adminForm');
				  	
				  ?>

</tbody>
 </table>

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

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

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

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

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

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

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

	<input type="hidden" name="option" value="com_dtregister" />

	<!-- Hidden variable-->

	<?php
       
	   if($m_s_title)

		{

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

			{

				$value=$arrTitle[$i];

			?>

				<input type="hidden" name="arr_title[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_firstname)

		{

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

			{

				$value=$arrFirstName[$i];

			?>

				<input type="hidden" name="arr_firstname[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_lastname)

		{

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

			{

				$value=$arrLastName[$i];

			?>

				<input type="hidden" name="arr_lastname[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_organization)

		{

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

			{

				$value=$arrOrganization[$i];

			?>

				<input type="hidden" name="arr_organization[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_address)

		{

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

			{

				$value=$arrAddress[$i];

			?>

				<input type="hidden" name="arr_address[]" value="<?php echo $value;?>" />

			<?php

			}

		}
		
		if($m_s_address2)

		{

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

			{

				$value=$arrAddress2[$i];

			?>

				<input type="hidden" name="arr_address2[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_city)

		{

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

			{

				$value=$arrCity[$i];

			?>

				<input type="hidden" name="arr_city[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_state)

		{

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

			{

				$value=$arrState[$i];

			?>

				<input type="hidden" name="arr_state[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_zip)

		{

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

			{

				$value=$arrZip[$i];

			?>

				<input type="hidden" name="arr_zip[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_country)

		{

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

			{

				$value=$arrCountry[$i];

			?>

				<input type="hidden" name="arr_country[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_email)

		{

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

			{

				$value=$arrEmail[$i];

			?>

				<input type="hidden" name="arr_email[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_phone)

		{

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

			{

				$value=$arrPhone[$i];

			?>

				<input type="hidden" name="arr_phone[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		//Hidden variables for custom fields

		if(isset($rowCustoms) && isset($_POST['current_member']))

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

		{

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$arrName="arr_".$name;;

			if(isset($$arrName) && $rowCustom->type != 6 && is_array($$arrName))

			{

				$arrName="arr_".$name;

				$arrValues=$$arrName;

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

				{

					$value=$arrValues[$j];

				if(is_array($value) && isset($value[0])){$value = $value[0];}elseif(is_array($value)){ $value= ""; }

				?>

					<input type="hidden" name="<?php echo $arrName; ?>[]" value="<?php echo $value ?>" />

				<?php

				}

			}else{
			   ?>
                 <input type="hidden" name="<?php echo $arrName; ?>[]" value="" />
               <?php	
			}

		}

	?>

	</form>
  <div style="display:none">
<iframe name="fileupload">

</iframe>
</div>
   
     <script type="text/javascript">
	  
DTjQuery(function(){
  DTjQuery('.upload').live('click',function(){
	   
	   DTjQuery(this.form).attr('target','fileupload');
	   prevtask = DTjQuery(this.form.task).val();
	   prevtype = DTjQuery(this.form.type).val();
	   var filesizes = DTjQuery(this).attr('filesize');
	   var filetype = DTjQuery(this).attr('filetype');
	   var name = DTjQuery(this).attr('filename');
	  
	   DTjQuery(this.form.type).val(name+'|'+filesizes+'|'+filetype);
	   
	   DTjQuery(this.form.task).val('fileupload');
	   DTjQuery(this.form.option).val('com_dtregister');
	   DTjQuery(this.form.option).val('com_dtregister');
	   
	   DTjQuery(this.form).submit();
	   
	   DTjQuery(this.form.task).val(prevtask);
	   DTjQuery(this.form.type).val(prevtype);
	   DTjQuery(this.form).attr('target','');
	   return false;
	});
})
	 </script>
<?php

}

function showEventEmailForm($option){

require("../components/com_dtregister/config.dtregister.php");

	jimport('joomla.html.select');

	$database = &JFactory::getDBO();

	$sql="Select distinct  eventId from #__dtregister_group_event";

	$database->setQuery($sql);

	$rowEvents=$database->loadObjectList();

	$arrEventIds=array();

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

	{

		$rowEvent=$rowEvents[$i];

		$arrEventIds[]=$rowEvent->eventId;

	}

	$sql="SELECT evdet_id,summary,dtstart,dtend FROM #__jevents_vevdetail WHERE evdet_id IN (".implode(",",$arrEventIds).")";

	$database->setQuery($sql);

	$rowEvents=$database->loadObjectList();

	$options=array();

	$options[]=JHTML::_('select.option',"0"," Select event ");

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

	{

		$rowEvent=$rowEvents[$i];

		$value=$rowEvent->evdet_id;

		$text=tmpl_event_name($event_show_date,$rowEvent->summary,get_date($rowEvent->dtstart,$rowEvent->dtend));

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

	}

	$lists['event_list']=JHTML::_('select.genericlist', $options,'event_id','','value','text','');

	HTML_groups::showEventEmailForm($option,$lists);

}

//Send mail to event's members

function sendMailToMembers($option)

{

	global $mainframe;

	$database = &JFactory::getDBO();

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

	$mail =& JFactory::getMailer();

	$config =& JFactory::getConfig();

	$eventId=JRequest::getInt( 'event_id', 0, 'post' );

	$subject=JRequest::getString( 'subject' );

	 $message=JRequest::get( null ,JREQUEST_ALLOWRAW );

	$message=$message['content'];

	//echo $_REQUEST['content'];

	$fromName=JRequest::getString( 'from_name');

	$fromEmail=JRequest::getVar( 'from_email');

	if(!$fromName)

	{

		$fromName=$DT_fromname;

	}

	if(!$fromEmail)

	{

		$fromEmail=$DT_mailfrom;

	}

	 if($eventId == 0){

		?>

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

        <?php

		exit;

	}

	if($subject == ''){

		?>

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

        <?php

		exit;

	}

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

		 ?>

       document.adminForm.task.value = '<?php echo $_REQUEST['task'];?>';

       DTjQuery('#emailRegitration').submit();

    <?php

		exit ;

	}

	//Get the eventId list
  
	$sql="Select a.userId ,  a.userEmail

		From #__dtregister_user as a

		where a.eventId=$eventId

		";
   $dt_evt = new Event($eventId);
	$database->setQuery($sql);

	$rowEmails=$database->loadObjectList();

	$email_flag = true ;

	$prev_user = 0 ;

	$sent_email = array();
    $bcc = JRequest::getVar( 'bcc', array(), 'post' );
	
	$bcc = explode(";",$bcc);
	foreach($bcc as $bccemail){
	   if($bccemail !="" && $message != "")
	   JUTility::sendMail( $fromEmail, $fromName,$bccemail,$subject,$message,1);
	}
	foreach($rowEmails as $user){
	    
		$dt_user = new DT_User($user->userId);
		$dt_user->event = $dt_evt ;
		$uMessage = thanks_email_tags($dt_user,$message);
		$email = $user->userEmail ;
		
		$subject = str_replace('[EVENT_DATE]',get_date($dt_evt->dtstart,$dt_evt->dtend),$subject);
       
	    $subject = str_replace('[EVENT_NAME]',$dt_evt->summary,$subject);
		if($user->userEmail !="" && $uMessage != "")
		JUTility::sendMail( $fromEmail, $fromName,$email,$subject,$uMessage,1);
		
		if($sendEmailToGroup && $dt_user->userType=="G"){
		   foreach($dt_user->get_members() as $member){
		      
			  $mMessage = thanks_email_members_tags($member,$message);
			  $email = $member->email ;
			 if($email !="" && $uMessage != "")
			 JUTility::sendMail( $fromEmail, $fromName,$email,$subject,$uMessage,1);
		   }
		}
	}
	
	$mainframe->redirect("index2.php?option=com_dtregister","Emails sent");

}

function deletegrpmember($option, $cid=array()){
  
  global $mainframe;
  $database = &JFactory::getDBO();
  $deleted = 0 ;
  for ($i=0,$n=count($cid);$i<$n;$i++){
     
	 $memberId=$cid[$i];
	 
	 $member =   new Member($memberId);
	 
	 $member->read();
	 
	 $userId = $member->getUserId() ;
	 if(!isset($user))
	 $user =  new DT_User($userId);
	
	 if((count($user->get_members()) - count($cid) + $deleted) >= 2){
	    $member->delete();
	    $deleted++ ;
	  
	 }else{
	  
	 }
	 
  }
  $mainframe->redirect("index2.php?option=com_dtregister&task=showmembers&gid=".$member->groupUserId."&event_id=".$member->groupUserId);
}

function  deletemember($option,$cid){

	global $mainframe;

	$database = &JFactory::getDBO();

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

	{

		$userid=$cid[$i];

		//$gtype= $_REQUEST["gtype"];

		$groupidqry="select groupId from #__dtregister_group where useid=$userid";

		$database->setQuery($groupidqry);

		$groupid=$database->loadResult();

		$amountqry="delete from #__dtregister_group_amount where groupId=$groupid";

		$database->setQuery($amountqry);

		$database->query();

		$gqry = "delete from #__dtregister_group_member where groupUserId =$groupid";

		$database->setQuery($gqry);

		$database->query();

		$groupqry="delete from #__dtregister_group where useid=$userid";

		$database->setQuery($groupqry);

		$database->query();
        $dt_user = new DT_user($userid);
		@unlink($dt_user->barcodePath); 
		$sqlqry="delete from #__dtregister_user where userId=$userid";

		$database->setQuery($sqlqry);

		if (!$database->query())

		{

			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

		}

	}

	//listregistrations($option);

	$mainframe->redirect("index2.php?option=com_dtregister&act=registrations");

}

function savemember($option,$id){

	include(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'config.dtregister.php');

	$database = &JFactory::getDBO();

	$userid=$id;

	$sql = "select * from #__dtregister_user where userId =".$userid ; 

   	$database->setQuery($sql);

	$old_data = $database->loadObject();

	if (isset($_POST["eventId"])){$eventId=JRequest::getVar("eventId",NULL,'POST');} else {$eventId="";}

    if (isset($_POST["title"])){$title=JRequest::getVar("title",NULL,'POST');} else {$title="";}
   
	if (isset($_POST["firstname"])){$firstname=JRequest::getVar("firstname",NULL,'POST');} else {$firstname="";}

	if (isset($_POST["lastname"])){$lastname=JRequest::getVar("lastname",NULL,'POST');} else {$lastname="";}

	if (isset($_POST["organization"])){$organization=JRequest::getVar("organization",NULL,'POST');} else {$organization="";}

	if (isset($_POST["address"])){$address=JRequest::getVar("address",NULL,'POST');} else {$address="";}
	
	if (isset($_POST["address2"])){$address2=JRequest::getVar("address2",NULL,'POST');} else {$address2="";}

	if (isset($_POST["city"])){$city=JRequest::getVar("city",NULL,'POST');} else {$city="";}

	if (isset($_POST["state"])){$state=JRequest::getVar("state",NULL,'POST');} else {$state="";}

	if (isset($_POST["country"])){$country=JRequest::getVar("country",NULL,'POST');} else {$country="";}

	if (isset($_POST["zip"])){$zip=JRequest::getVar("zip",NULL,'POST');} else {$zip="";}

	if (isset($_POST["phone"])){$phone=JRequest::getVar("phone",NULL,'POST');} else {$phone="";}

	if (isset($_POST["email"])){$email=JRequest::getVar("email",NULL,'POST');} else {$email="";}

	if (isset($_POST["pay_later_paid"])){$payLaterPaid=JRequest::getVar("pay_later_paid",NULL,'POST');} else {$payLaterPaid="";}

	if (isset($_POST["payment_type"])){$payment_type=$_POST["payment_type"];} else {$payment_type="";}

	if (isset($_POST["amount"])){$amount=$_POST["amount"];} else {$amount="";}

	if (isset($_POST["user_id"])){$user_id=JRequest::getVar("user_id",NULL,'POST');} else {$user_id="";}
	
	if (isset($_POST["attend"])){$attend=JRequest::getVar("attend",NULL,'POST');} else {$attend=0;}
	
	if (isset($_POST["cancel"])){$cancel=JRequest::getVar("cancel",NULL,'POST');} else {$cancel=0;}
	
	if (isset($_POST["paid_amount"])){$paid_amount=JRequest::getVar("paid_amount",NULL,'POST');} else {$paid_amount=0;}
	
	if (isset($_POST["transaction_id"])){$transaction_id=JRequest::getVar("transaction_id",NULL,'POST');} else {$transaction_id="";}

    if(($user_id>0) && $cb_integrated)

	{

		//Get the user detail

		$sql="Select a.id,a.email,b.*

			From #__users As a

			Inner Join #__comprofiler As b

			On a.id=b.user_id

			Where a.id=$user_id

			";

		$database->setQuery($sql);

		$rowProfile = $database->loadObject();

	}

	$firstname = (isset($rowProfile->firstname) && $firstname=="")?$rowProfile->firstname:$firstname ;

	$lastname = (isset($rowProfile->lastname) && $lastname=="")?$rowProfile->lastname:$lastname ;

	$organization = (isset($rowProfile->cb_company) && $organization=="")?$rowProfile->cb_company:$organization ;

	$address = (isset($rowProfile->cb_address) && $address=="")?$rowProfile->cb_address:$address ;

	$city =(isset($rowProfile->cb_city) && $city=="")?$rowProfile->cb_city:$city ;

	$state = (isset($rowProfile->cb_state)  && $state=="")?$rowProfile->cb_state:$state ;

	$zip = (isset($rowProfile->cb_zipcode) && $zip=="")?$rowProfile->cb_zipcode:$zip ;

	$phone = (isset($rowProfile->cb_phone) &&  $phone=="")?$rowProfile->cb_phone:$phone ;

	$email = (isset($rowProfile->email) &&  $email=="")?$rowProfile->email:$email ;
	$discount_code_sql ="" ;
     if(isset($_POST['discount_code'])){
	     $dis_code =  new DiscountCode();
		 $codes = $dis_code->getcodes(" code = ".$database->Quote($_POST['discount_code']));
		 if($codes){
		    $code = $codes[0] ;
			$discount_code_sql  = " , discount_code_id = ".$code->id ;
		 }else{
		    $code = false ;
		 }
		 
	 }else{
	    
	 }
	 
	 $dt_user = new DT_User($userid);
	 
	 
	 $paid_amount  =  str_replace(",",".",$paid_amount);
	 $sqlqry="update #__dtregister_user set userFirstName=".$database->Quote($firstname).",userLastName= ".$database->Quote($lastname).",

userOrganization=".$database->Quote($organization).",userAddress=".$database->Quote($database->getEscaped($address)).",userCity='$city',userState='$state', eventId = '$eventId' , attend = '$attend' , userAddress2= ".$database->Quote($database->getEscaped($address2)).",  userTitle= ".$database->Quote($title).",

userCountry='$country',userZip='$zip',userPhone='$phone',userEmail='$email',pay_later_paid='$payLaterPaid' , payment_type = '$payment_type' , paid_amount = '$paid_amount' , user_id='$user_id' , cancel= $cancel , transaction_id = ".$database->Quote($transaction_id)." $discount_code_sql where userId=$userid";

	$database->setQuery($sqlqry);
    
	$id=$userid;

	if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

	}
    if($payLaterPaid != $dt_user->pay_later_paid && $paid_status_change_msg_send){
		$dt_user->pay_later_paid = $payLaterPaid ;
		$dt_user = new DT_User($userid);
		paidStatusNotification($dt_user);
	}
    $dt_user = new DT_User($userid);

    $dt_user->set_amount(str_replace(",",".",$amount));
    if($old_data->cancel != $dt_user->cancel && $status_change_msg_send){
	   statusNotification($dt_user);
	}
	/*$query="update #__dtregister_group_amount set amount='$amount'

   where groupId=$userid";

	$database->setQuery($query);

	if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

	}*/

	//Update custom fields

	$sql="Select * From #__dtregister_fields where published=1 order by ordering";

	$database->setQuery($sql);

	$rowCustoms=$database->loadObjectList();

	if(count($rowCustoms))

	{

		$arrFields=array();

		$arrValues=array();

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

		{

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$arrFields[]=$name;

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

			if($rowCustom->type==3 && $value!=NULL)

			{

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

			}

			if($rowCustom->type==2){

				$value = addslashes($value);

			}

			$arrValues[]=$value;

		}

		$sql="Update #__dtregister_user

			Set

			";

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

		{

			if($i<($n-1))

			{

				$sql.= $arrFields[$i]."= ".$database->Quote($arrValues[$i]).",";

			}

			else

			{

				$sql.= $arrFields[$i]."= ".$database->Quote($arrValues[$i])." ";

			}

		}

		$sql.=" Where userId=$id";

		$database->setQuery($sql);

		if(!$database->query())

		{

			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

			exit();

		}

	}

	//End update custom fields

    global $mainframe ;

	$redirect = JRequest::getVar("redirect",NULL,'POST');

	if($redirect == 'no'){ 

		$mainframe->redirect("index2.php?option=com_dtregister&task=editmemberA&hidemainmenu=1&id=".$userid);

		exit  ; 

	}
	
	$mainframe->redirect("index2.php?option=com_dtregister&act=registrations");

}

function editmember($option,$memberid){

	$database = &JFactory::getDBO();

     require("../components/com_dtregister/config.dtregister.php");

	 $showmembersql="select a.*,b.summary , b.dtstart ,b.dtend , ga.amount from

  #__dtregister_user a,#__jevents_vevdetail b  ,#__dtregister_group_amount ga ,  #__dtregister_group dg where  ga.groupId = dg.groupId and a.userId=dg.useid and a.eventId=b.evdet_id and a.userId=$memberid";

	$database->setQuery($showmembersql);

 $database->getErrorMsg();

	$rows=$database->loadObjectList();

	$eventId=$rows[0]->eventId;

	$dt_event =  new Event($eventId);
	$options = array();

	$options[]=JHTML::_('select.option', '','Select payment method');

	$options[]=JHTML::_('select.option', 'Credit Card (Authorize.net)',JText::_('AUTH_NET'));
    $options[]=JHTML::_('select.option', 'Echeck',JText::_('ECHECK'));
	$options[]=JHTML::_('select.option', 'GoogleCheckout', JText::_( 'DT_GOOGLE_CHECKOUT' ));
	
	$options[]=JHTML::_('select.option', 'Paypal',JText::_('PAYPAL'));
   $options[]=JHTML::_('select.option', 'Eway', JText::_( 'DT_EWAY' ));
	
    $options[]=JHTML::_('select.option', 'ideal',JText::_('DT_PAY_IDEAL'));
	$options[]=JHTML::_('select.option', 'idealRabo', JText::_( 'DT_PAY_IDEAL_LITE' ));
	$options[]=JHTML::_('select.option', 'NetDeposit', JText::_( 'DT_NETDEPOSIT' ));
	$options[]=JHTML::_('select.option', 'Mail',JText::_('DT_MAILIN_PAYMENT'));

	$options[]=JHTML::_('select.option', 'Phone',JText::_('DT_CALLIN_PAYMENT'));

	$options[]=JHTML::_('select.option', 'At_door',JText::_('DT_PAY_AT_DOOR'));

	$options[]=JHTML::_('select.option', 'Free',JText::_('DT_FREE'));
    
	$lists["payment_type"]=JHTML::_('select.genericlist',$options,'payment_type','','value','text',$rows[0]->payment_type);

	$options = array();

	$options[]=JHTML::_('select.option', '',JText::_('DT_SELECT_USER'));

	$query = "select * from #__users order by name";

	$database->setQuery($query);

	$users=$database->loadObjectList();

	foreach($users as $user){

		$options[]=JHTML::_('select.option', $user->id,$user->name." (".$user->username.")");

	}

	$lists["users"]=JHTML::_('select.genericlist',$options,'user_id','','value','text',$rows[0]->user_id);

   	$options = array();

	$options[]=JHTML::_('select.option', '','Select Event');

    $evt = new Event();

	$events  =  $evt->findall();

	  foreach($events as $event){

		$options[]=JHTML::_('select.option', $event->eventId,tmpl_event_name($event_show_date,$event->summary,get_date($event->dtstart,$event->dtend)));

      }

  $lists["events"]=JHTML::_('select.genericlist',$options,'eventId','','value','text',$rows[0]->eventId);
  
  	$options = array();

	$options[]=JHTML::_('select.option', '',JText::_('DT_SELECT_STATUS'));

    $options[] = JHTML::_('select.option', 0, JText::_('DT_ACTIVE'));
	
	 $options[] = JHTML::_('select.option', 1, JText::_('DT_CANCELLED'));
	 
	 $options[] = JHTML::_('select.option', 2, JText::_('DT_PENDING'));
	 
  $lists["status"]=JHTML::_('select.genericlist',$options,'cancel','','value','text',$rows[0]->cancel);
  
  $options = array();
  
 // $options[]=JHTML::_('select.option', '1',JText::_('YES'));
 // $options[]=JHTML::_('select.option', '2',JText::_('NO'));
  $lists["attend"]=JHTML::_('select.booleanlist','attend','',$rows[0]->attend);
   $titles = explode("|",$titleoptions);
	$temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

	foreach($titles as $title){
	
		$temp[] = JHTML::_('select.option', $title, $title);
	
	}
	        
	$titles = $temp;
			
    $lists["titles"] = JHTML::_('select.genericlist',$temp,'title', 'class="inputbox" size="1"', 'value', 'text',$rows[0]->userTitle);
	
	HTML_groups::editmember($option,$rows,$lists,$dt_event);

}

function listregistrations($option){

	global $mainframe;

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

	jimport('joomla.html.pagination');

	jimport('joomla.html.select');

	$listLimit = $mainframe->getCfg( 'list_limit', 10 );

	$database = &JFactory::getDBO();

	//Get the list of event
    
	if(isset($_POST['attend'])){
	   
	   $_SESSION['liststate']['records']['event_id'] = JRequest::getInt('event_id',0);
	   $_SESSION['liststate']['records']['verified'] = JRequest::getInt('verified',0);
	   $_SESSION['liststate']['records']['attend'] = JRequest::getInt('attend',0);
	   $_SESSION['liststate']['records']['cancel'] = JRequest::getVar('cancel','');
	   $_SESSION['liststate']['records']['order'] = JRequest::getVar('order','');
	   $_SESSION['liststate']['records']['dir'] = JRequest::getVar('dir','');
	   $_SESSION['liststate']['records']['archive'] = JRequest::getVar('archive','');
	   $_SESSION['liststate']['records']['search'] = JRequest::getVar('search','');
	   
	}else{
	   
	   if(isset($_SESSION['liststate']['records'])){
	      
		  foreach($_SESSION['liststate']['records'] as $key=>$value){
		     
			 JRequest::setVar($key,$value);
			 
		  }
	   }
	   
	}
	
	$eventId=JRequest::getInt('event_id',0);

	$paymentVerified=JRequest::getInt('verified',0);
    $attend = JRequest::getInt('attend',-1);
	if(isset($_REQUEST['search'])){
	  $cancel = JRequest::getVar('cancel','','post');
	}else{
	  $cancel = "" ;
	}
	
	$order=JRequest::getVar( 'order' );

	$sort=JRequest::getVar( 'dir' );
	
	$search = JRequest::getVar('search','') ;
	$archive = JRequest::getVar('archive',-1) ;

	if (!$sort){$sort='DESC';}

	if($eventId>0){

		$where=" a.eventId=$eventId ";

	}else {

		$where="1=1";

	}

	//Get the list of events

	$sql="Select distinct eventId from #__dtregister_group_event";

	$database->setQuery($sql);

	$rowEvents=$database->loadObjectList();

	$arrEventIds=array();

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

	{

		$rowEvent=$rowEvents[$i];

		$arrEventIds[]=$rowEvent->eventId;

	}
    if(count($arrEventIds) > 0 ){
	   
		$sql="SELECT evdet_id,summary,dtstart , dtend FROM #__jevents_vevdetail WHERE evdet_id IN (".implode(",",$arrEventIds).") order by dtstart desc";
	
		$database->setQuery($sql);
	
		$rowEvents=$database->loadObjectList();
    
	}
	$options=array();

	$options[]=JHTML::_('select.option',"0"," Select event ");
    if(count($arrEventIds)>0)
	for ($i=0,$n=count($rowEvents);$i<$n;$i++)

	{

		$rowEvent=$rowEvents[$i];

		$value=$rowEvent->evdet_id;

		$text=tmpl_event_name($event_show_date,$rowEvent->summary,get_date($rowEvent->dtstart,$rowEvent->dtend));

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

	}

	$lists['event_list'] = JHTML::_('select.genericlist', $options,'event_id',' onchange="submit()" ','value','text',$eventId);

		$options=array();

	   $options[]=JHTML::_('select.option', '1', JText::_( 'YES' ));//

	   $options[]=JHTML::_('select.option', '0', JText::_( 'NO' ));

	$lists['show_failed'] = JHTML::_('select.genericlist', $options,'verified',' onchange="submit()" ','value','text',$paymentVerified);

	$options=array();

       $options[]=JHTML::_('select.option', '-1', JText::_( 'DT_NONE' ));//
	   $options[]=JHTML::_('select.option', '1', JText::_( 'YES' ));//

	   $options[]=JHTML::_('select.option', '0', JText::_( 'NO' ));

	$lists['show_attend'] = JHTML::_('select.genericlist', $options,'attend',' onchange="submit()" ','value','text',$attend);
	//Get limit start

	//$limit 		= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $listLimit ) );
    $options = array();

	$options[]=JHTML::_('select.option', '',JText::_('DT_SELECT_STATUS'));

    $options[] = JHTML::_('select.option', 0, JText::_('DT_ACTIVE'));
	
	 $options[] = JHTML::_('select.option', 1, JText::_('DT_CANCELLED'));
	 
	 $options[] = JHTML::_('select.option', 2, JText::_('DT_PENDING'));
	 
  $lists["status"]=JHTML::_('select.genericlist',$options,'cancel',' onchange="submit()"','value','text',$cancel);
	$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );

	$limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );

	$orderBy = 'a.userId';

	switch ($order) {

		 case 'confirmNum':

			$orderBy = 'a.confirmNum';

			break;

		case 'type':

			$orderBy = 'a.payment_type';

			break;

		case 'name':

			$orderBy = 'a.userLastName';

			break;

		case 'org':

			$orderBy = 'a.userOrganization';

			break;

		case 'email':

			$orderBy = 'a.userEmail';

			break;

		case 'event':

			$orderBy = 'a.eventId';

			break;

		case 'amount':

			$orderBy = 'e.amount';

			break;

		case 'date':

			$orderBy = 'a.register_date';

			break;

		case 'paid':

			$orderBy = 'a.pay_later_paid';

			break;

		case 'members':

			$orderBy = 'e.numberOfPerson';

			break;
         case 'due_amount':

			$orderBy = 'a.due_payment';

		 break;
        case 'attend':

		   $orderBy = 'a.attend';
		break;
		case 'cancel':

		   $orderBy = 'a.cancel';
		break;
		default:

			$orderBy = 'a.userId';

			break;

	}

	//End get limit data
	
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$sqlSearch = "" ;
    if($search!=""){
	   
	   $sqlSearch = "AND (a.userFirstName LIKE '%{$search}%' OR a.userLastName LIKE '%{$search}%' OR a.userOrganization LIKE '%{$search}%'  OR a.userEmail LIKE '%{$search}%' OR a.confirmNum LIKE '%{$search}%' OR a.userCity LIKE '%{$search}%' OR a.userState LIKE '%{$search}%' OR a.userCountry LIKE '%{$search}%' OR a.userZip LIKE '%{$search}%' ) ";
	    
	}
	if ($paymentVerified == 0){	$payVerified = ' AND ((payment_type <> "Authorize.net") || (a.pay_later_paid=0 and payment_type="Authorize.net"))';	} else { $payVerified = ' AND (a.pay_later_paid=1 and payment_type="Authorize.net")';}
    $attend_sql = "" ;
    if($attend >=0 ){
	    
		$attend_sql = " And a.attend=".$attend;
	}
	$cancel_sql = "" ;
	
    if($cancel !=""){
	   $cancel_sql = " And a.cancel=".$cancel;
	}

   switch($archive){
      case -1:
	      $archivesql = " and evt.archive=0 ";
	  break;
	  
	  case 0: // all events
	       $archivesql = " ";
	  break;
	  
	  case 1:
	       $archivesql = " and evt.archive=1 ";
	  break;
   }
$listsql="SELECT a.userId as id, a.cancel , a.userOrganization,a.userFirstName,a.userLastName,a.userEmail,a.userType,a.register_date,a.eventId,a.confirmNum,a.payment_type,a.pay_later_option,a.pay_later_paid,d.summary, d.dtstart ,d.dtend , a.payment_verified, a.paid_amount , 

e.numberOfPerson,e.amount,b.groupId,dis.code , a.due_payment, a.attend 

FROM

#__dtregister_user a  inner join

#__dtregister_group b on  a.userId= b.useid

inner join

#__jevents_vevdetail d  on a.eventId=d.evdet_id

inner join #__dtregister_group_event evt  on evt.eventId = d.evdet_id 

inner join

 #__dtregister_group_amount e on b.groupId=e.groupId

left join #__dtregister_codes dis on dis.id = a.discount_code_id

WHERE     $where    $payVerified $attend_sql $cancel_sql $archivesql $sqlSearch   group by a.userId ORDER BY $orderBy $sort";

$database->setQuery($listsql);

 echo $database->getErrorMsg();
	$rowCounts=$database->loadObjectList();

	$total=count($rowCounts);

	require_once( JPATH_SITE . '/administrator/includes/pageNavigation.php' );

	$pageNav = new JPagination( $total, $limitstart, $limit  );

	$database->setQuery($listsql,$limitstart,$limit);

	//Build event select box

	$rows=$database->loadObjectList();

	if ($sort=='ASC'){$sort='DESC';} else if ($sort=='DESC'){$sort='ASC';}

	HTML_groups::showregistrations( $option, $rows,$pageNav,$eventId,$lists,$sort);

}

function showmembers($option,$groupid){

	global $mainframe;

	$database = &JFactory::getDBO();

	$eventId=JRequest::getInt( 'event_id',0,'post');

	//Get custom fields list
    
	$sql="Select fe.field_id From #__dtregister_field_event fe inner join #__dtregister_fields df on fe.field_id=df.id where fe.event_id=$eventId and (fe.showed=1 or (fe.showed =2 and df.showed=1)) and fe.group_behave <>2";

	$database->setQuery($sql);

	$rows=$database->loadObjectList();

	$arrFieldIds=array();

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

	{

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

	}

	$rowCustoms = array();

	if(count($arrFieldIds))

	{

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

		$database->setQuery($sql);

		//echo $database->getQuery();

		if($database->getErrorMsg())

			echo $database->getErrorMsg();

		$rowCustoms=$database->loadObjectList();

	}

	$listsql="select * from  #__dtregister_group_member

	where groupUserId=$groupid order by groupMemberId";

	$database->setQuery($listsql);

	$rows=$database->loadObjectList();

	HTML_groups::showmembers($option,$rows,$rowCustoms);

}

function exportEventSettings($option){

	global $mainframe;

	$database = &JFactory::getDBO();

	$database->setQuery( "SELECT * , date(b.dtstart) eventdate from #__dtregister_group_event a

	INNER JOIN #__jevents_vevdetail b ON a.eventid = b.evdet_id

	LEFT JOIN #__dtregister_categories c ON a.category = c.categoryId  group by b.evdet_id ");

	$events = $database->loadObjectList();

	HTML_groups::exportEventSettings( $option, $events );

}

function showGroups( $option ) {

	global $mainframe;

   require("../components/com_dtregister/config.dtregister.php");

	$database = &JFactory::getDBO();

	jimport('joomla.html.pagination');

	jimport('joomla.html.select');

	$catid = $mainframe->getUserStateFromRequest( "groupid{$option}", 'groupId', 0 );

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );

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

	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

	$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );

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

	$eventId=JRequest::getInt( 'event_id',0);

	$publish=JRequest::getInt( 'publish',"-1");

	$where = array();

	//$where[]=" a.eventid=b.id and a.category=c.categoryId ";

	if ($search) { $where[] = " b.summary LIKE '%$search%' "; }

	if($eventId>0){ $where[]=" eventId=$eventId "; }

    if($publish =="1" || $publish =="0"){

	  $where[] = " a.publish = '$publish' ";

	}

	# Get the total number of records
   
	$database->setQuery( "SELECT count(*) FROM #__dtregister_group_event a

		INNER JOIN #__jevents_vevdetail b ON a.eventid = b.evdet_id

		LEFT JOIN #__dtregister_categories c ON a.category = c.categoryId "

	. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "").

      "ORDER BY c.ordering ,a.eventId , a.ordering ASC , b.dtstart ASC "  );

	$total = $database->loadResult();

	echo $database->getErrorMsg();

	//include_once( "includes/pageNavigation.php" );

	$pageNav = new JPagination( $total, $limitstart, $limit  );
   $archive = JRequest::getVar('archive',-1) ;
   
   switch($archive){
      case -1:
	      $archivesql = " and a.archive=0 ";
	  break;
	  
	  case 0: // all events
	       $archivesql = " ";
	  break;
	  
	  case 1:
	       $archivesql = " and a.archive=1 ";
	  break;
   }
   
    if($eventListOrder==1){
	  
	   $ordering = " b.dtstart desc  ";
	}else if($eventListOrder==0){
	   $ordering = " b.dtstart asc  ";
	}else{
	   $ordering = " a.ordering ASC ";
	}
   $ordering = " a.ordering ASC ";
   $sql = "SELECT a. * , b.summary, b.dtstart, b.dtend 

		FROM #__dtregister_group_event a

		INNER JOIN #__jevents_vevdetail b ON a.eventid = b.evdet_id $archivesql  

		LEFT JOIN #__dtregister_categories c ON a.category = c.categoryId ";

	if(count($where)){ $sql.=" Where ".implode(" AND ",$where ); }

 	//$sql .= "order by c.ordering , a.ordering ASC , b.dtstart ASC" ;

    $sql .= "order by c.ordering ,$ordering " ;

	$database->setQuery( $sql,$pageNav->limitstart,$pageNav->limit);

	$rows = $database->loadObjectList();

	if ($database->getErrorNum()) {

		echo $database->stderr();

		return false;

	}

	//Get the list of events

	$sql="Select distinct eventId from #__dtregister_group_event";

	$database->setQuery($sql);

	$rowEvents=$database->loadObjectList();

	$arrEventIds=array();

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

	{

		$rowEvent=$rowEvents[$i];

		$arrEventIds[]=$rowEvent->eventId;

	}

	if (count($arrEventIds)>0){

		$sql="SELECT evdet_id,summary,dtstart ,dtend FROM #__jevents_vevdetail WHERE evdet_id IN (".implode(",",$arrEventIds).") order by dtstart desc";

		$database->setQuery($sql);

		$rowEvents=$database->loadObjectList();

	} else {

		$rowEvents = NULL;

	}

	$options=array();

	$options[]=JHTML::_('select.option',"0"," Select event ");

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

	{

		$rowEvent=$rowEvents[$i];

		$value=$rowEvent->evdet_id;

		$text=tmpl_event_name($event_show_date,$rowEvent->summary,get_date($rowEvent->dtstart,$rowEvent->dtend));

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

	}

	$lists['event_list']=JHTML::_('select.genericlist', $options,'event_id',' onchange="submit()" ','value','text',$eventId);

	HTML_groups::showGroups( $option, $rows, $search, $pageNav,$lists);

}

##############################################################################

function newGroups( $option, $uid ) {

	global $DT_mailfrom;

	$database = &JFactory::getDBO();

	$row = new DTmosGroups( $database );

	# Load the row from the db table

	$row->load( $uid );

	if (!$uid) {

		# Initialise new record

		$row->published = 0;

	}

	HTML_groups::newGroups( $option, $row, $statuslist );

}

function editGroups( $option, $uid ) {

	global $mosConfig_dbprefix;

	$mosConfig_live_site = JURI::base( true );

	$database = &JFactory::getDBO();

	$aqry="SELECT a.*, b.summary from #__dtregister_group_event a, #__jevents_vevdetail b WHERE a.eventid=b.evdet_id and a.slabId= $uid";

	$database->setQuery($aqry);

		$res=$database->loadObjectList();

		$memberArr[]=$res[0]->memberTotal;

		$amountArr[]=$res[0]->regGroupRate;

		$amountArrI[]=$res[0]->registerAmountIndividual;

		$amountArrPer[]=$res[0]->regGroupPerRate;

		$title = $res[0]->summary;

		$lateFee = $res[0]->latefee;

		$dateLateFee = $res[0]->latefeedate;

		$eml=$res[0]->email;

		$eventId=$res[0]->eventId;

		$maxRegistrations=$res[0]->max_registrations;

		$registrationType=$res[0]->registration_type;

		$topmsg=$res[0]->topmsg;

		$cutOffDate=$res[0]->cut_off_date;

		$discount_type=$res[0]->discount_type;

		$discount_amount=$res[0]->discount_amount;

		$thksmsg=$res[0]->thksmsg;

		$thksmsg_set=$res[0]->thksmsg_set;

		$event_describe=$res[0]->event_describe;

		$event_describe_set=$res[0]->event_describe_set;

		$terms_conditions_set=$res[0]->terms_conditions_set;

		$terms_conditions_msg=$res[0]->terms_conditions_msg;

		$category=$res[0]->category;

		$max_group_size=$res[0]->max_group_size;

    $waiting_list=$res[0]->waiting_list;

    $public=$res[0]->public;

		$use_discountcode = $res[0]->use_discountcode;
		
    $startDate = $res[0]->startdate;

		$bird_discount_type = $res[0]->bird_discount_type;

		$bird_discount_amount = $res[0]->bird_discount_amount;

		$bird_discount_date = $res[0]->bird_discount_date;

		$publish = $res[0]->publish;

		$payment_option = $res[0]->payment_option;
    $partial_payment = $res[0]->partial_payment;
    $partial_amount  = $res[0]->partial_amount;
		$partial_minimum_amount  = $res[0]->partial_minimum_amount;
		
		$pay_later_thk_msg_set  = $res[0]->pay_later_thk_msg_set;
		$pay_later_thk_msg  = $res[0]->pay_later_thk_msg;
		
	HTML_groups::editGroups(

		$option,

		$memberArr,

		$amountArr,

		$amountArrI,

		$amountArrPer,

		$lateFee,

		$dateLateFee,

		$title,

		$uid,

		$eml,

		$eventId,

		$maxRegistrations,

		$registrationType,

		$topmsg,

		$cutOffDate,

		$discount_type,

		$discount_amount,

		$thksmsg,

		$thksmsg_set,

		$event_describe,

		$event_describe_set,

		$terms_conditions_set,

		$terms_conditions_msg,

		$category,

		$waiting_list,

		$max_group_size,

		$public,

		$use_discountcode,

		$startDate ,

		$bird_discount_date,

		$bird_discount_type,

		$bird_discount_amount,

		$publish,

		$payment_option,
		$partial_payment,
		$partial_amount,
		$partial_minimum_amount,
		$pay_later_thk_msg_set,
		$pay_later_thk_msg

	);

}

##############################################################################

function saveGroups( $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	if(JRequest::getVar('id')=="")

	{

		if(JRequest::getVar('slabId')=="")

		$mainframe->redirect( "index2.php?option=$option&task=new", "Select an event first." );

		else

		{

			for($i=0;$i<=10;$i++)

			{

				$maxRegistrations=JRequest::getInt( 'max_registrations',0,'post');

				if((@$_POST['member'][$i]!="" && (@$_POST['amount'][$i] !="")) || ($i==0))

				{

					if($i<=0){

						$query = "INSERT INTO #__dtregister_group_event(

							eventId,

							memberTotal,

							regGroupRate,

							regGroupPerRate,

							registerAmountIndividual,

							latefee,

							latefeedate,

							email,

							max_group_size,

							max_registrations,

							public,

							use_discountcode

							) VALUES (

							'".$_POST['slabId']."','".

							$_POST['member'][$i]."','".

							amountToDot($_POST['amount'][$i])."','".

							amountToDot($_POST['amount'][$i])."','".

							amountToDot($_POST['amount'][$i])."','".

							amountToDot($_POST['late_fee'])."','".

							$_POST['late_fee_date']."','".

							$_POST['email']."','".

							JRequest::getInt( 'max_group_size',0,'post')."','".

							$maxRegistrations."','".

							$_POST['public']."','".

							$_POST['use_discountcode']."'

							)";

					}else{

						$query = "INSERT INTO #__dtregister_group_event(

							eventId,

							memberTotal,

							regGroupRate,

							regGroupPerRate,

							registerAmountIndividual,

							latefee,

							latefeedate,

							email,

							max_group_size,

							max_registrations,

							public,

							use_discountcode

							) VALUES ('".

							$_POST['slabId']."','".

							$_POST['member'][$i]."','".

							amountToDot($_POST['amount'][$i])."','".

							amountToDot($_POST['amountper'][$i])."','".

							amountToDot($_POST['amountper'][$i])."','".

							amountToDot($_POST['late_fee'])."','".

							$_POST['late_fee_date']."','".

							$_POST['email']."','".

							JRequest::getInt( 'max_group_size',0,'post')."','".

							$maxRegistrations."','".

							$_POST['public']."','".

							$_POST['use_discountcode']."'

							)";

					}

				    $database->setQuery($query);

					if(!$database->query()) die(mysql_error());

				}

			}

			//Will update here

			//Get custom fieds here

			$eventId=JRequest::getVar('slabId');

			$last_insert_slabId=$database->insertid();

			  $query = "SELECT ordering FROM #__dtregister_group_event WHERE eventId = '".$last_insert_slabId."'";

			$database->setQuery($query);

			$result = $database->query();

			if($data=$database->loadResult($result)){

			}else{

				$data = $last_insert_slabId;

			}

			 $query = "UPDATE #__dtregister_group_event SET ordering ='".$data."' WHERE slabId='".$last_insert_slabId."'";

			//Update max registrations

			$database = &JFactory::getDBO();

			$maxRegistrations=JRequest::getInt( 'max_registrations', 0, 'post');

      if(!$maxRegistrations)

			$maxRegistrations=0;

			$registrationType=JRequest::getString( 'registration_type', 0, 'post');

			$topmsg=JRequest::getString( 'topmsg',"","post",JREQUEST_ALLOWRAW );

			$thksmsg=JRequest::getString( 'thksmsg' ,"","post",JREQUEST_ALLOWRAW);

			$thksmsg_set=JRequest::getInt( 'thksmsg_set' );

			$waiting_list=JRequest::getInt( 'waiting_list',0, 'post');

			$event_describe=JRequest::getString( 'event_describe' ,"","post",JREQUEST_ALLOWRAW);

			$event_describe_set=JRequest::getInt( 'event_describe_set' );

			$terms_conditions_set=JRequest::getInt( 'terms_conditions_set' );

			$terms_conditions_msg=JRequest::getString( 'terms_conditions_msg' ,"","post",JREQUEST_ALLOWRAW);

			$cutOffDate=JRequest::getVar( 'cut_off_date');

			$category=JRequest::getInt( 'category' );

			$max_group_size=JRequest::getInt( 'max_group_size', 0, 'post');

			//Get discount info

			$discountType=JRequest::getInt( 'discount_type',0, 'post');

			$discountAmount=JRequest::getVar( 'discount_amount' );

			$public=JRequest::getInt('public');

			$use_discountcode = JRequest::getInt('use_discountcode');

	  	if(!$discountAmount)

			$discountAmount=0;

			$sql="UPDATE #__dtregister_group_event SET

				max_registrations=$maxRegistrations,

				registration_type='$registrationType',

				topmsg=".$database->Quote($topmsg).",

				cut_off_date='$cutOffDate',

				discount_type='$discountType',

				discount_amount='".amountToDot($discountAmount)."',

				thksmsg=".$database->Quote($thksmsg).",

				thksmsg_set=".$database->Quote($thksmsg_set).",

				event_describe=".$database->Quote($event_describe).",

				event_describe_set=".$database->Quote($event_describe_set).",

				terms_conditions_set=".$database->Quote($terms_conditions_set).",

				terms_conditions_msg=".$database->Quote($terms_conditions_msg).",

				category='$category',

				max_group_size='$max_group_size',

				waiting_list='$waiting_list',

				public='$public',

				use_discountcode='$use_discountcode'

				WHERE eventId=$eventId";

			$database->setQuery($sql);

			$database->query();

			$sql="Select * From #__dtregister_fields where published=1";

			$database->setQuery($sql);

			$rowFields=$database->loadObjectList();

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

			{

				$rowField=$rowFields[$i];

				$id=$rowField->id;

				$name=$rowField->name;

				$showed=JRequest::getInt( 'field_'.$name,0,'post');

				$group=JRequest::getInt( 'group_'.$name,0,'post');

        $required=$showed?JRequest::getInt( 'required_field_'.$name ):0;

				$sql="Insert Into #__dtregister_field_event(field_id,event_id,showed,group_behave,required) Values($id,$eventId,$showed,$group,$required)";

				$database->setQuery($sql);

				$database->query();

				if($database->getErrorMsg())

				{

					echo $database->getErrorMsg();

				}

			}

		}

	}

	else

	{

		for($i=0;$i<count(JRequest::getInt('member'));$i++)

		{

			if(@$_POST['member'][$i]!="" && (@$_POST['amount'][$i] !="" && @$_POST['amountper'][$i] != "") )

			{

				$query ="update #__dtregister_group_event set

					memberTotal=".(int)($_POST['member'][0]).

					" ,regGroupRate='".amountToDot($_POST['amount'][$i]).

					"',registerAmountIndividual='".amountToDot($_POST['amountper'][$i]).

					"',regGroupPerRate='".amountToDot($_POST['amountper'][$i]).

					"',latefee='".amountToDot(JRequest::getVar('late_fee')).

					"',email='".JRequest::clean('email').

					"',max_group_size='".JRequest::getVar('max_group_size').

					"',latefeedate='".JRequest::getVar('late_fee_date').

					"',waiting_list='".JRequest::getVar('waiting_list').

					"',public='".JRequest::getInt('public').

					"' where slabId=".JRequest::getVar('id');

				$database->setQuery($query);

				if(!$database->query()) die(mysql_error());

			}

		}

		//Update custom fields here

		$eventId=JRequest::getInt('event_id', 0, 'post');

		$maxRegistrations=JRequest::getInt( 'max_registrations',0, 'post');

		$registrationType=JRequest::getString( 'registration_type');

		$topmsg=JRequest::getString( 'topmsg',"","post",4 );

		$thksmsg=JRequest::getString( 'thksmsg',"","post",4 );

		$thksmsg_set=JRequest::getInt( 'thksmsg_set' );

		$event_describe=JRequest::getString( 'event_describe',"","post",JREQUEST_ALLOWRAW );

		$event_describe_set=JRequest::getInt( 'event_describe_set' );

		$terms_conditions_set=JRequest::getInt( 'terms_conditions_set' );

		$terms_conditions_msg=JRequest::getString( 'terms_conditions_msg' ,"","post",JREQUEST_ALLOWRAW);

		$max_group_size=JRequest::getInt( 'max_group_size' );

		$cutOffDate=JRequest::getVar( 'cut_off_date');

		$category=JRequest::getInt( 'category' );

		//Get discount info

		$discountType=JRequest::getInt( 'discount_type',0, 'post');

		$discountAmount=amountToDot(JRequest::getVar( 'discount_amount' ));

		$public=JRequest::getInt( 'public',0,'post');

		$use_discountcode = JRequest::getInt('use_discountcode',0,'post');

		//Update max registrations here

		 $sql="UPDATE #__dtregister_group_event SET

			max_registrations='$maxRegistrations',

			registration_type='$registrationType',

			topmsg=".$database->Quote($topmsg).",

			cut_off_date='$cutOffDate',

			discount_type='$discountType',

			discount_amount='".amountToDot($discountAmount)."',

			thksmsg=".$database->Quote($thksmsg).",

			thksmsg_set=".$database->Quote($thksmsg_set).",

			event_describe=".$database->Quote($event_describe).",

			event_describe_set=".$database->Quote($event_describe_set).",

			terms_conditions_set=".$database->Quote($terms_conditions_set).",

			terms_conditions_msg=".$database->Quote($terms_conditions_msg).",

			category='$category',

			email = '".JRequest::getVar('email')."',

			max_group_size='$max_group_size',

			public='$public',

			use_discountcode='$use_discountcode'

			WHERE eventId=$eventId";

		$database->setQuery($sql);

		$database->query();

		$sql="Delete From #__dtregister_field_event Where event_id=$eventId";

		$database->setQuery($sql);

		$database->query();

		$flds = new Custom_field();
		$fields =  array();
		$flds->findtree(0,$fields);
		
		$config_set =  array();
		foreach($fields as $id=>$rowField)

		{

			$name=$rowField->name;
			
            if($rowField->parent_id!=0){
			   
				JRequest::setVar('field_'.$name,$config_set[$rowField->parent_id]['showed']);
				JRequest::setVar('group_'.$name,$config_set[$rowField->parent_id]['group_behave']);
				JRequest::setVar('required_field_'.$name,$config_set[$rowField->parent_id]['required']);
			}
			$showed=JRequest::getInt( 'field_'.$name); 
			
			if($showed==-1){
			    $objField = new mosField($database);
			    $objField->load($id);
				//$showed = $objField->showed ;
				$group = $objField->group_behave ;
				$required = $objField->required ;
			}else{
			   $group=JRequest::getInt( 'group_'.$name );

			   $required=$showed?JRequest::getInt( 'required_field_'.$name ):0;
			
			}
            $config_set[$id] =  array('showed'=>$showed,'group_behave'=>$group,'required'=>$required);
			$sql="Insert Into #__dtregister_field_event(field_id,event_id,showed,group_behave,required) Values($id,$eventId,$showed,$group,$required)";

			$database->setQuery($sql);
			
			$database->getQuery($sql);

			$database->query();

			if($database->getErrorMsg())

			{

				echo $database->getErrorMsg();

			}

		}
		
	}
    
	$evt =  new Event($eventId);

	if(isset($_REQUEST['discount_code_id']))

	$evt->assign_discountcodes($_REQUEST['discount_code_id']);

	$evt->assign_article(JRequest::getInt('article_id'));

	$evt->save_field('detail_link_show',JRequest::getInt('detail_link_show'));
	
	$evt->save_field('category',JRequest::getInt('category'));
	
	$evt->save_field('latefee',amountToDot(JRequest::getVar('late_fee')));

	$evt->save_field('latefeedate',JRequest::getVar('late_fee_date'));

	$evt->save_field('email',JRequest::getVar('email'));

	$evt->save_field('show_registrant',JRequest::getVar('show_registrant'));

    $evt->save_field('startdate',JRequest::getVar('startdate'));

	$evt->save_field('bird_discount_type',JRequest::getVar('bird_discount_type'));

	$evt->save_field('bird_discount_amount',amountToDot(JRequest::getVar('bird_discount_amount')));

	$evt->save_field('bird_discount_date',JRequest::getVar('bird_discount_date'));

    $evt->save_field('publish',JRequest::getVar('publish'));

    $evt->save_field('partial_payment',JRequest::getVar('partial_payment'));

	$evt->save_field('cancel_refund_status',JRequest::getVar('cancel_refund_status'));
   
	$evt->save_field('publish',JRequest::getVar('publish'));

	$evt->save_field('location_id',JRequest::getVar('location_id'));

	$evt->save_field('payment_option',JRequest::getVar('payment_option'));
	$evt->save_field('partial_amount',JRequest::getVar('partial_amount'));
	$evt->save_field('partial_minimum_amount',JRequest::getVar('partial_minimum_amount'));
	
	$evt->save_field('edit_fee',JRequest::getVar('edit_fee'));
	$evt->save_field('cancelfee_enable',JRequest::getVar('cancelfee_enable'));
	$evt->save_field('cancel_date',JRequest::getVar('cancel_date'));
	$evt->save_field('change_date',JRequest::getVar('change_date'));
	$evt->save_field('excludeoverlap',JRequest::getVar('excludeoverlap'));
	
	$evt->save_field('pay_later_thk_msg_set',JRequest::getVar('pay_later_thk_msg_set'));
	
	$evt->save_field('pay_later_thk_msg',JRequest::getString( 'pay_later_thk_msg' ,"","post",JREQUEST_ALLOWRAW));
	
	$evt->save_field('thanksmsg_set',JRequest::getVar('thanksmsg_set'));
	
	$evt->save_field('detail_itemid',JRequest::getVar('detail_itemid'));
	
	$evt->save_field('tax_enable',JRequest::getVar('tax_enable'));
    $evt->save_field('tax_amount',JRequest::getVar('tax_amount'));
    	
	$evt->save_field('thanksmsg',JRequest::getString( 'thanksmsg' ,"","post",JREQUEST_ALLOWRAW));

    $files = JRequest::getVar('copy_files',array());

	foreach($files as $key => $file){

	  $dt_file = new DT_file();

	  $dt_file->path = $file ;

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

	}

	$evt->save_files(JRequest::getVar('event_files', null, 'files', 'array'));

	$evt->save_config(JRequest::getVar('config'));
	
	$evt->save_prerequisite(JRequest::getVar('prerequisite'));
	$evt->save_prerequisite_category(JRequest::getVar('prerequisite_category'));
  
	//$evt->save_field('detail_link_type',JRequest::getInt('detail_link_type'));

	//$evt->save_field('plugin_link_type',JRequest::getInt('plugin_link_type'));
	
	$task = JRequest::getVar( 'task' );
   if($task=="applyevent"){
       $mainframe->redirect( "index2.php?cid[]=".$evt->slabId."&option=com_dtregister&task=edit&act=groups" );
   }else{
      $mainframe->redirect( "index2.php?option=$option" );
   }
	
}

##############################################################################

function removeGroups( $uid, $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	$eventId=JRequest::getInt('eventId', 0, 'post');

	if (!is_array( $uid ) || count( $uid ) < 1) {

		echo "<script> alert('Select an item to delete.'); window.history.go(-1);</script>\n";

		exit;

	}

	if (count($uid )>1) {

		$cids = implode( ',', $uid );

		$sqry="DELETE FROM #__dtregister_group_event WHERE  slabId IN ($cids)";

		$database->setQuery( $sqry );

	}else{

		$sqry= "DELETE FROM #__dtregister_group_event WHERE slabId = $uid[0]";

		$database->setQuery( $sqry);

	}

	if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

	}

	$mainframe->redirect( "index2.php?option=$option" );

}

##############################################################################

function cancelGroups( $option ) {

	global $mainframe;

	$mainframe->redirect( "index2.php?option=$option" );

}

##############################################################################

function loadtab(){

   ob_clean();

   $tab=JRequest::getVar('type');

   $database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	require_once( JPATH_SITE.'/components/com_dtregister/class.dtregister.php');
   
   if($tab !='loadeditor'){

       JHTML::_('behavior.calendar');

       jimport('joomla.html.pane');

	   jimport('joomla.html.select');
	
	  $pane =& JPane::getInstance('tabs');

   }
  
	jimport( 'joomla.html.editor');

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

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

    jimport('joomla.application.component.model');

	include( JPATH_SITE.'/administrator/components/com_dtregister/models/jomsocial.php');

	$editor =& JFactory::getEditor();

   include(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'view'.DS.'config'.DS.'tab.'.$tab.'.php');

   if($tab !='loadeditor'){

     die ;

   }

}

function showConfig($option){

    include( JPATH_SITE.'/components/com_dtregister/config.dtregister.php');
	jimport('joomla.html.pane');

	jimport('joomla.html.select');

	$pane =& JPane::getInstance('tabs');

	$editor =& JFactory::getEditor();

?>

	<form action="index2.php" method="POST" name="adminForm">

  <table cellpadding="4" cellspacing="0" border="0" width="100%">

  <tr><td width="100%" class="sectionname">

  </td></tr>

  </table>

  <table width="100%" align="left" border="0" cellpadding="4" cellspacing="2" class="adminForm">

<!-- ******************************************************************************************************************	-->

<tr align="center" valign="middle">

<td align="left" valign="top">

<b>DT Register</b> enables you to take online registrations through your Authorize.net payment gateway, Google Checkout, iDeal and/or PayPal. You can also setup offline (Pay Later) payments.

<br /><br />Be sure to watch our video tutorials which will walk you through all of the setup and configuration options.

<br />* To create your menu landing page for registration, simply create a Component menu item for DT Register.

<br /><br />&copy;2006 DTH Development.  For tutorials, support and more information, go to <b><a href="http://www.DTHDevelopment.com" target="_blank">http://www.DTHDevelopment.com</a></b>.<br />

</td></tr>

<tr align="center" valign="middle"><td align="left" valign="top">&nbsp;</td></tr>

<!-- ******************************************************************************************************************	-->

 <!-- cb integration -->

 <tr>

 	<td>

 		<!-- Separate data by tab-->

 		<table width="100%">

 			<tr>

 				<td width="100%">

 					<?php	

					jimport('joomla.application.component.model');

					include( JPATH_SITE.'/administrator/components/com_dtregister/models/jomsocial.php');

					echo $pane->startPane('dtregister');

 						//$tabs->startTab(JText::_( 'DT_REGISTER_GENERAL' ),'dtregister1');

 						echo $pane->startPanel(JText::_( 'DT_REGISTER_GENERAL' ),'dtregister1');

 					?>

 						<div class="dtTabs" id='general'>

                        </div>

	 					<?php

	 						echo $pane->endPanel();

                            echo $pane->startPanel(JText::_( 'DT_EVENT_LISTING' ),'dtregister6');

							?>

                               <div class="dtTabs" id='event_listing'>

                               </div>					  

                            <?php

                            echo $pane->endPanel();

	 						              echo $pane->startPanel(JText::_( 'DT_REGISTER_EMAIL' ),'dtregister2');

	 					    ?>

                                <div class="dtTabs1" id='message'>
                                    <?php

		 include(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'view'.DS.'config'.DS.'tab.message.php');

		 ?>
                        
                               </div>		

	 					<?php

	 						echo $pane->endPanel();

	 						echo $pane->startPanel(JText::_( 'DT_EMAILS' ),'dtregister9');

	 					?>

                          <div class="dtTabs1" id='email'>
                             <?php

		 include(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'view'.DS.'config'.DS.'tab.email.php');

		 ?>
                        
                          </div>	

	 					<?php

	 						echo $pane->endPanel();

	 						echo $pane->startPanel(JText::_( 'DT_REGISTER_PAYMENT' ),'dtregister3');

	 					?>

                            <div class="dtTabs" id='payment'>

                            </div>	

	 					<?php

	 						echo $pane->endPanel();

	 						echo $pane->startPanel(JText::_( 'DT_REGISTER_FIELDS' ),'dtregister4');

	 					?>

								  <div class="dtTabs" id='field'>

                            </div>	

	 					<?php

	 						echo $pane->endPanel();

							echo $pane->startPanel(JText::_( 'DT_REGISTER_REGISTRANTS' ),'dtregister5');

							?>

                                 <div class="dtTabs1" id='registrant'>
                                      <?php

		 include(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'view'.DS.'config'.DS.'tab.registrant.php');

		 ?>
                        
                            </div>	

                              <?php

							              echo $pane->endPanel();

                            echo $pane->startPanel(JText::_( 'DT_USER_PANEL' ),'dtregister6');

							              ?>

                                   <div class="dtTabs1" id='userpanel'>
 <?php

		 include(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'view'.DS.'config'.DS.'tab.userpanel.php');

		 ?>
                        
                                     </div>	

                            <?php

							echo $pane->endPanel();

							echo $pane->startPanel(JText::_( 'DT_JOMSOCIAL' ),'dtregister7');

                            ?>

                            <?php

                            $model = & JModel::getInstance('Model','Jomsocial');

							$options =  array();

							  $options = $model->getFieldsOption();

							?>

                             <div class="dtTabs" id='jomsocial'>

                                     </div>	

                            <?php
                            
							echo $pane->endPanel();
                            
							echo $pane->startPanel(JText::_( 'DT_BARCODE' ),'dtregister8');
							?>
                             <div class="dtTabs" id='barcode'>

                             </div>	
							   
                            <?php
							echo $pane->endPanel();
	 						echo $pane->endPane();

	 					?>

	 				</td>

	 			</tr>

	 		</table>

	 	</td>

	 </tr>

</table>

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

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

</form>

   <?php  

           $document	=& JFactory::getDocument();

		   //JHTML::script('jquery.js','components/com_dtregister/assets/js/');
		   
		    $document->addScript( JURI::root(true)."/components/com_dtregister/assets/js/jquery.js");

    ?>

   <script type="text/javascript" >
      
       if(typeof(jQuery) != "undefined"){
	     DTjQuery = jQuery.noConflict();
	  }
      DTjQuery(function(){

	     DTjQuery('.dtTabs').each(function(){

             DTjQuery(this).load("index.php?option=com_dtregister&task=loadtab&type="+DTjQuery(this).attr('id'));
			/*if(jQuery(this).attr('id') == 'jomsocial'){

			   jQuery(this).load("index.php?option=com_dtregister&task=loadtab&type="+jQuery(this).attr('id'),function(data){ loadeditor() ; });

			}else{

			   jQuery(this).load("index.php?option=com_dtregister&task=loadtab&type="+jQuery(this).attr('id'));

			}*/

		 });
		
	  });
     
	  function loadeditor(){

		 <?php

		// include(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'view'.DS.'config'.DS.'tab.loadeditor.php');

		 ?>

	  }
     
   </script>

<?php

}
##############################################################################

function saveConfig ($option, $cardtype, $cardtext,$thankmsg) {

	global $mainframe;

	$database = &JFactory::getDBO();

    $fields = JRequest::getVar("field");

	  $fields = implode("','",array_keys($fields));

	  $sql = "update #__dtregister_fields set attendee_list=0";

	  $database->setQuery($sql);

      $database->query();

	  $sql = "update #__dtregister_fields set attendee_list=1 where id in('".$fields."')";

	  $database->setQuery($sql);

	  $database->query();

	$arrFields=array(); // DB column names

	$arrValues=array(); // DB column values
	
	
	
	
	
	
	$arrFields[]='show_price_tax';

	$arrValues[]=JRequest::getVar("show_price_tax");
	
	$arrFields[]='csv_separator';

	$arrValues[]=JRequest::getVar("csv_separator");
	
	$arrFields[]='barcode_rotation';

	$arrValues[]=JRequest::getVar("barcode_rotation");
	
	$arrFields[]='barcode_type';

	$arrValues[]=JRequest::getVar("barcode_type");
	
	$arrFields[]='barcode_image_type';

	$arrValues[]=JRequest::getVar("barcode_image_type");
	
	$arrFields[]='barcodeDpi';

	$arrValues[]=JRequest::getVar("barcodeDpi");
	
	$arrFields[]='barcodeThick';

	$arrValues[]=JRequest::getVar("barcodeThick");
	
	$arrFields[]='barcode_resolution';

	$arrValues[]=JRequest::getVar("barcode_resolution");
	
	$arrFields[]='barcode_font_size';

	$arrValues[]=JRequest::getVar("barcode_font_size");
	
	$arrFields[]='barcode_enable';

	$arrValues[]=JRequest::getVar("barcode_enable");
	
	
	
	
	$arrFields[]='confirm_number_start';

	$arrValues[]=JRequest::getVar("confirm_number_start");
	
	$arrFields[]='usercreation';

	$arrValues[]=JRequest::getVar("usercreation");
	
	$arrFields[]='confirm_number_prefix';

	$arrValues[]=JRequest::getVar("confirm_number_prefix");
	
	$arrFields[]='confirm_number_type';

	$arrValues[]=JRequest::getVar("confirm_number_type");
	
	$arrFields[]='paid_default_status';

	$arrValues[]=JRequest::getVar("paid_default_status");
	
	$arrFields[]='partial_default_status';

	$arrValues[]=JRequest::getVar("partial_default_status");
	
	$arrFields[]='paylater_default_status';

	$arrValues[]=JRequest::getVar("paylater_default_status");
	
	$arrFields[]='private_event_notification';

	$arrValues[]=JRequest::getVar("private_event_notification");
	
	$arrFields[]='private_event_redirect';

	$arrValues[]=JRequest::getVar("private_event_redirect");
	
	$arrFields[]='eway_customerid';

	$arrValues[]=JRequest::getVar("eway_customerid");
	
	$arrFields[]='ewaytype';

	$arrValues[]=JRequest::getVar("ewaytype");
	
	$arrFields[]='ewaymode';

	$arrValues[]=JRequest::getVar("ewaymode");
	
	$arrFields[]='netdeposit_clientid';

	$arrValues[]=JRequest::getVar("netdeposit_clientid");
	
	$arrFields[]='netdeposit_clientcode';

	$arrValues[]=JRequest::getVar("netdeposit_clientcode");
	
	$arrFields[]='netdeposit_acctnum';

	$arrValues[]=JRequest::getVar("netdeposit_acctnum");
	
	$arrFields[]='eventListOrder';

	$arrValues[]=JRequest::getVar("eventListOrder");
	
	 $conf = new DTConfig();
     if($conf->getConfig('eventListOrder') != JRequest::getVar("eventListOrder")){
	   $conf->updateEventorder( JRequest::getVar("eventListOrder"));
	 }
	 
	$arrFields[]='googlemerchid';

	$arrValues[]=JRequest::getVar("googlemerchid");
    
	$arrFields[]='googleapikey';

	$arrValues[]=JRequest::getVar("googleapikey");
	
	$arrFields[]='googlemerchid';

	$arrValues[]=JRequest::getVar("googlemerchid");
	
	$arrFields[]='googlemode';

	$arrValues[]=JRequest::getVar("googlemode");
	
	$arrFields[]='DT_mailfrom';

	$arrValues[]=JRequest::getVar("DT_mailfrom");
	
	$arrFields[]='DT_fromname';

	$arrValues[]=JRequest::getVar("DT_fromname");
	
	$arrFields[]='paid_status_change_msg_send';

	$arrValues[]=JRequest::getVar("paid_status_change_msg_send");
	
	$arrFields[]='status_change_msg_send';

	$arrValues[]=JRequest::getVar("status_change_msg_send");
	
	$arrFields[]='map_joms_firstname';

	$arrValues[]=JRequest::getVar("map_joms_firstname");
	
	//------------------------------------------------------
	
	$arrFields[]='map_joms_firstname';

	$arrValues[]=JRequest::getVar("map_joms_firstname");
	
	$arrFields[]='map_joms_firstname';

	$arrValues[]=JRequest::getVar("map_joms_firstname");
	
	$arrFields[]='map_joms_lastname';

	$arrValues[]=JRequest::getVar("map_joms_lastname");
	
	$arrFields[]='map_joms_org';

	$arrValues[]=JRequest::getVar("map_joms_org");
	
	$arrFields[]='map_joms_title';

	$arrValues[]=JRequest::getVar("map_joms_title");
	
	$arrFields[]='map_joms_address';

	$arrValues[]=JRequest::getVar("map_joms_address");
	
	$arrFields[]='map_joms_address2';

	$arrValues[]=JRequest::getVar("map_joms_address2");
	
	$arrFields[]='map_joms_city';

	$arrValues[]=JRequest::getVar("map_joms_city");
	
	$arrFields[]='map_joms_state';

	$arrValues[]=JRequest::getVar("map_joms_state");
	
	$arrFields[]='map_joms_zip';

	$arrValues[]=JRequest::getVar("map_joms_zip");
	
	$arrFields[]='map_joms_country';

	$arrValues[]=JRequest::getVar("map_joms_country");
	
	$arrFields[]='map_joms_phone';

	$arrValues[]=JRequest::getVar("map_joms_phone");
	
	//-----------------------------------------------------
    $arrFields[]='event_title_link';

	$arrValues[]=JRequest::getVar("event_title_link");

	$arrFields[]='event_search_show';

	$arrValues[]=JRequest::getVar("event_search_show");
	
	$arrFields[]='event_filter_show';

	$arrValues[]=JRequest::getVar("event_filter_show");
	
	$arrFields[]='month_filter_show';

	$arrValues[]=JRequest::getVar("month_filter_show");
	
	$arrFields[]='timecheck';

	$arrValues[]=JRequest::getVar("timecheck");
	
    $arrFields[]='cbviewonly';

	$arrValues[]=JRequest::getVar("cbviewonly");
	
	$arrFields[]='prerequisite_paid';

	$arrValues[]=JRequest::getVar("prerequisite_paid");
	
	$arrFields[]='prerequisite_attend';

	$arrValues[]=JRequest::getVar("prerequisite_attend");  
    
  $arrFields[]='sendEmailToGroup';

	$arrValues[]=JRequest::getVar("sendEmailToGroup");  
	
  $arrFields[]='userpanelmessage';

	$arrValues[]=JRequest::getString("userpanelmessage","","post",JREQUEST_ALLOWRAW);
	
	$arrFields[]='email_cancel_confirm';

	$arrValues[]=JRequest::getString("email_cancel_confirm","","post",JREQUEST_ALLOWRAW);
	
	$arrFields[]='email_change_confirm';

	$arrValues[]=JRequest::getString("email_change_confirm","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='payment_confirm';

	$arrValues[]=JRequest::getString("payment_confirm","","post",JREQUEST_ALLOWRAW);
	
	$arrFields[]='changefee_type';

	$arrValues[]=JRequest::getVar("changefee_type");
	
  $arrFields[]='changefee_enable';

	$arrValues[]=JRequest::getVar("changefee_enable");
	
  $arrFields[]='changefee';

	$arrValues[]=JRequest::getVar("changefee");
	
  $arrFields[]='cancelfee_type';

	$arrValues[]=JRequest::getVar("cancelfee_type");
	
  $arrFields[]='cancelfee_enable';

	$arrValues[]=JRequest::getVar("cancelfee_enable");
	
  $arrFields[]='cancelfee';

	$arrValues[]=JRequest::getVar("cancelfee");

  $arrFields[]='location_img_w';

  $arrValues[]=JRequest::getVar("location_img_w");

	$arrFields[]='location_img_h';

  $arrValues[]=JRequest::getVar("location_img_h");

	$arrFields[]='googlekey';

  $arrValues[]=JRequest::getVar("googlekey");

	$arrFields[]='linktogoogle';

  $arrValues[]=JRequest::getVar("linktogoogle");

	$arrFields[]='showlocation';

  $arrValues[]=JRequest::getVar("showlocation");
    
  $arrFields[]='event_date_show';

  $arrValues[]=JRequest::getVar("event_date_show");

	$arrFields[]='timeformat';

	$arrValues[]=JRequest::getVar("timeformat");

	$arrFields[]='displaytime';

	$arrValues[]=JRequest::getVar("displaytime");

	$arrFields[]='currency_separator';

	$arrValues[]=JRequest::getVar("currency_separator");

	$arrFields[]='partner_id';

	$arrValues[]=JRequest::getVar("partner_id");

	$arrFields[]='idealmode';

	$arrValues[]=JRequest::getVar("idealmode");

    $arrFields[]='idealLiteMerchantId';

	$arrValues[]=JRequest::getVar("idealLiteMerchantId");
	
	$arrFields[]='idealLiteHashKey';

	$arrValues[]=JRequest::getVar("idealLiteHashKey");
	
	$arrFields[]='idealLiteMode';

	$arrValues[]=JRequest::getVar("idealLiteMode");

    $arrFields[]='event_show_date';

	$arrValues[]=JRequest::getVar("event_show_date");

	$arrFields[]='show_past_event';

	$arrValues[]=JRequest::getVar("show_past_event");

	$arrFields[]='show_group_members';

	$arrValues[]=JRequest::getVar("show_group_members");

	$arrFields[]='registrant_message';

	$arrValues[]=JRequest::getString("registrant_message","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='button_color';

	$arrValues[]=JRequest::getVar("button_color");

	$arrFields[]='registrant_city';

	$arrValues[]=JRequest::getVar("registrant_city");

	$arrFields[]='registrant_organization';

	$arrValues[]=JRequest::getVar("registrant_organization");

	$arrFields[]='registrant_address';

	$arrValues[]=JRequest::getVar("registrant_address");

	$arrFields[]='registrant_zip';

	$arrValues[]=JRequest::getVar("registrant_zip");

	$arrFields[]='registrant_country';

	$arrValues[]=JRequest::getVar("registrant_country");

	$arrFields[]='registrant_state';

	$arrValues[]=JRequest::getVar("registrant_state");

	$arrFields[]='registrant_list';

	$arrValues[]=JRequest::getVar("registrant_list");

    $arrFields[]='titleoptions';

	$arrValues[]=JRequest::getVar("titleoptions");

	$arrFields[]='registrant_avatar_height';

	$arrValues[]=JRequest::getVar("registrant_avatar_height");

	$arrFields[]='registrant_avatar_width';

	$arrValues[]=JRequest::getVar("registrant_avatar_width");

	$arrFields[]='registrant_cb_linked';

	$arrValues[]=JRequest::getVar("registrant_cb_linked");

	$arrFields[]='registrant_name';

	$arrValues[]=JRequest::getVar("registrant_name");

	$arrFields[]='registrant_username';

	$arrValues[]=JRequest::getVar("registrant_username");

	$arrFields[]='registrant_registered_date';

	$arrValues[]=JRequest::getVar("registrant_registered_date");

	$arrFields[]='registrant_show_avatar';

	$arrValues[]=JRequest::getVar("registrant_show_avatar");

	$capacity_column=JRequest::getInt( 'capacity_column',1, 'POST');

	$arrFields[]='capacity_column';

	$arrValues[]=$capacity_column;

	$arrFields[]='event_list_number';

	$arrValues[]=JRequest::getInt( 'event_list_number','20', 'POST');

	$arrFields[]='front_link_type';

	$arrValues[]= JRequest::getVar("front_link_type");

	$registered_column=JRequest::getInt( 'registered_column',1, 'POST');

	$arrFields[]='registered_column';

	$arrValues[]=$registered_column;

	$show_registration_button=JRequest::getInt( 'show_registration_button',1,'POST');

	$arrFields[]='show_registration_button';

	$arrValues[]=$show_registration_button;

	$merchid = JRequest::getVar("merchid");

	$arrFields[]='merchid';

	$arrValues[]=$merchid;

	$transkey = JRequest::getVar("transkey");

	$arrFields[]='transkey';

	$arrValues[]=$transkey;

   $overlap_event_msg = JRequest::getString("overlap_event_msg","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='overlap_event_msg';

	$arrValues[]=$overlap_event_msg;
	
	 $status_change_msg = JRequest::getString("status_change_msg","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='status_change_msg';

	$arrValues[]=$status_change_msg;
	$thanksemail = JRequest::getString("thanksemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='thanksemail';

	$arrValues[]=$thanksemail;
	 $paid_status_change_msg = JRequest::getString("paid_status_change_msg","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='paid_status_change_msg';

	$arrValues[]=$paid_status_change_msg;
	
	

	$thanksmsg = JRequest::getString("thanksmsg","","post",JREQUEST_ALLOWRAW);
	
	$arrFields[]='thanksmsg';

	$arrValues[]=$thanksmsg;
	
	$prerequisite_event_msg = JRequest::getString("prerequisite_event_msg","","post",JREQUEST_ALLOWRAW);
	
	$arrFields[]='prerequisite_event_msg';

	$arrValues[]=$prerequisite_event_msg;
	
	$pay_later_thk_msg = JRequest::getString("pay_later_thk_msg","","post",JREQUEST_ALLOWRAW);
	
	$arrFields[]='pay_later_thk_msg';

	$arrValues[]=$pay_later_thk_msg;

	$subthanksemail = JRequest::getString("subthanksemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='subthanksemail';

	$arrValues[]=$subthanksemail;
	
	$subchangestatusemail = JRequest::getString("subchangestatusemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='subchangestatusemail';

	$arrValues[]=$subchangestatusemail;
	
	$subpaidstatusemail = JRequest::getString("subpaidstatusemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='subpaidstatusemail';

	$arrValues[]=$subpaidstatusemail;
	
	$upsubpaymentemail = JRequest::getString("upsubpaymentemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='upsubpaymentemail';

	$arrValues[]=$upsubpaymentemail;
	
	$upsubcancelemail = JRequest::getString("upsubcancelemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='upsubcancelemail';

	$arrValues[]=$upsubcancelemail;
	
	$upsubchangeemail = JRequest::getString("upsubchangeemail","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='upsubchangeemail';

	$arrValues[]=$upsubchangeemail;
	
	$topmsg=JRequest::getString("topmsg","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='topmsg';

	$arrValues[]=$topmsg;

	$date_format=JRequest::getString("date_format");

	$arrFields[]='date_format';

	$arrValues[]=$date_format;

	$terms=JRequest::getString("terms_conditions_msg","","post",JREQUEST_ALLOWRAW);

	$arrFields[]='terms_conditions_msg';

	$arrValues[]=$terms;

	$paypalmode = JRequest::getVar('paypalmode');

	$arrFields[]='paypalmode';

	$arrValues[]=$paypalmode;

	$authnetmode = JRequest::getVar('authnetmode');

	$arrFields[]='authnetmode';

	$arrValues[]=$authnetmode;

	$cardtype=JRequest::getVar('cardtype');

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

	$arrFields[]='cardtype';

	$arrValues[]=$cardtype;

	$loginnameARB = JRequest::get('loginnameARB');

	$arrFields[]='loginnameARB';

	$arrValues[]=$loginnameARB;

	$transactionkeyARB = JRequest::get('transactionkeyARB');

	$arrFields[]='transactionkeyARB';

	$arrValues[]=$transactionkeyARB;

	$host=$_REQUEST['host'];

	$arrFields[]='host';

	$arrValues[]=$host;

	$path=$_REQUEST['path'];

	$arrFields[]='path';

	$arrValues[]=$path;

	$authpayoption=JRequest::get('authpayoption');

	$arrFields[]='authpayoption';

	$arrValues[]=$authpayoption;

	$paymentmethod = JRequest::getVar('paymentmethod','','post','ARRAY');

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

	$arrFields[]='paymentmethod';

	$arrValues[]=$paymentmethod;

	$paypalid = JRequest::getVar('paypalid');

	$arrFields[]='paypalid';

	$arrValues[]=$paypalid;

	$regtypeallowed = JRequest::get('regtypeallowed');

	$arrFields[]='regtypeallowed';

	$arrValues[]=$regtypeallowed;

	/*$discountType=JRequest::get("discount_type");

	$arrFields[]='discount_type';

	$arrValues[]=$discountType;

	$discountAmount=JRequest::get("discount_amount");

	$arrFields[]='discount_amount';

	$arrValues[]=$discountAmount;

*/

	$echecknetmode = JRequest::getVar('echecknetmode');

	$arrFields[]='echecknetmode';

	$arrValues[]=$echecknetmode;

	$fullEventMessages=JRequest::getString('full_message',"","post",JREQUEST_ALLOWRAW);

	$arrFields[]='full_message';

	$arrValues[]=$fullEventMessages;

	$cut_off_date_message=JRequest::getString('cut_off_date_message','','post',JREQUEST_ALLOWRAW);

	$arrFields[]='cut_off_date_message';

	$arrValues[]=$cut_off_date_message;

	$waiting_msg=JRequest::getString('waiting_msg',"","post",JREQUEST_ALLOWRAW);

	$arrFields[]='waiting_msg';

	$arrValues[]=$waiting_msg;

	$cb_integrated=JRequest::getVar('cb_integrated',0,'POST');

	$arrFields[]='cb_integrated';

	$arrValues[]=$cb_integrated;

	$security_image_check=JRequest::getBool('security_image_check',0,'POST');

	$arrFields[]='security_image_check';

	$arrValues[]=$security_image_check;

	$price_column=JRequest::getInt('price_column',0);

	$arrFields[]='price_column';

	$arrValues[]=$price_column;

	$currency_code=JRequest::getString('currency_code','USD');

	$arrFields[]='currency_code';

	$arrValues[]=$currency_code;
  
	$p_s_title=JRequest::getInt('p_s_title',1);

	$arrFields[]='p_s_title';

	$arrValues[]=$p_s_title;
	
	$p_r_title=JRequest::getInt('p_r_title',1);

	$arrFields[]='p_r_title';

	$arrValues[]=$p_r_title;
	
	$f_s_title=JRequest::getInt('f_s_title',1);

	$arrFields[]='f_s_title';

	$arrValues[]=$f_s_title;
	
	$f_r_title=JRequest::getInt('f_r_title',1);

	$arrFields[]='f_r_title';

	$arrValues[]=$f_r_title;
	
	$m_s_title=JRequest::getInt('m_s_title',1);

	$arrFields[]='m_s_title';

	$arrValues[]=$m_s_title;
	
	$m_r_title=JRequest::getInt('m_r_title',1);

	$arrFields[]='m_r_title';

	$arrValues[]=$m_r_title;
	
	$p_s_organization=JRequest::getInt('p_s_organization',1);

	$arrFields[]='p_s_organization';

	$arrValues[]=$p_s_organization;

	$p_r_organization=JRequest::getInt('p_r_organization',1);

	$arrFields[]='p_r_organization';

	$arrValues[]=$p_r_organization;

	$p_s_address=JRequest::getInt('p_s_address',1);

	$arrFields[]='p_s_address';

	$arrValues[]=$p_s_address;

	$p_r_address=JRequest::getInt('p_r_address',1);

	$arrFields[]='p_r_address';

	$arrValues[]=$p_r_address;

	$p_s_city=JRequest::getInt('p_s_city',1);

	$arrFields[]='p_s_city';

	$arrValues[]=$p_s_city;

	$p_r_city=JRequest::getInt('p_r_city',1);

	$arrFields[]='p_r_city';

	$arrValues[]=$p_r_city;

	$p_s_state=JRequest::getInt('p_s_state',1);

	$arrFields[]='p_s_state';

	$arrValues[]=$p_s_state;

	$p_r_state=JRequest::getInt('p_r_state',1);

	$arrFields[]='p_r_state';

	$arrValues[]=$p_r_state;

	$p_s_zip=JRequest::getInt('p_s_zip',1);

	$arrFields[]='p_s_zip';

	$arrValues[]=$p_s_zip;

	$p_r_zip=JRequest::getInt('p_r_zip',1);

	$arrFields[]='p_r_zip';

	$arrValues[]=$p_r_zip;

	$p_s_country=JRequest::getInt('p_s_country',1);

	$arrFields[]='p_s_country';

	$arrValues[]=$p_s_country;

	$p_r_country=JRequest::getInt('p_r_country',1);

	$arrFields[]='p_r_country';

	$arrValues[]=$p_r_country;

	$p_s_phone=JRequest::getInt('p_s_phone',1);

	$arrFields[]='p_s_phone';

	$arrValues[]=$p_s_phone;

	$p_r_phone=JRequest::getInt('p_r_phone',1);

	$arrFields[]='p_r_phone';

	$arrValues[]=$p_r_phone;

	$f_s_organization=JRequest::getInt('f_s_organization',1);

	$arrFields[]='f_s_organization';

	$arrValues[]=$f_s_organization;

	$f_r_organization=JRequest::getInt('f_r_organization',1);

	$arrFields[]='f_r_organization';

	$arrValues[]=$f_r_organization;

     $f_s_address2=JRequest::getInt('f_s_address2',1);

	$arrFields[]='f_s_address2';

	$arrValues[]=$f_s_address2;

	$f_r_address2=JRequest::getInt('f_r_address2',1);

	$arrFields[]='f_r_address2';

	$arrValues[]=$f_r_address2;
	 
	$p_s_address2=JRequest::getInt('p_s_address2',1);

	$arrFields[]='p_s_address2';

	$arrValues[]=$p_s_address2;

	$p_r_address2=JRequest::getInt('p_r_address2',1);

	$arrFields[]='p_r_address2';

	$arrValues[]=$p_r_address2;
	
	$m_s_address2=JRequest::getInt('m_s_address2',1);

	$arrFields[]='m_s_address2';

	$arrValues[]=$m_s_address2;

	$m_r_address2=JRequest::getInt('m_r_address2',1);

	$arrFields[]='m_r_address2';

	$arrValues[]=$m_r_address2;
	 
	$f_s_address=JRequest::getInt('f_s_address',1);

	$arrFields[]='f_s_address';

	$arrValues[]=$f_s_address;

	$f_r_address=JRequest::getInt('f_r_address',1);

	$arrFields[]='f_r_address';

	$arrValues[]=$f_r_address;

	$f_s_city=JRequest::getInt('f_s_city',1);

	$arrFields[]='f_s_city';

	$arrValues[]=$f_s_city;

	$f_r_city=JRequest::getInt('f_r_city',1);

	$arrFields[]='f_r_city';

	$arrValues[]=$f_r_city;

	$f_s_state=JRequest::getInt('f_s_state',1);

	$arrFields[]='f_s_state';

	$arrValues[]=$f_s_state;

	$f_r_state=JRequest::getInt('f_r_state',1);

	$arrFields[]='f_r_state';

	$arrValues[]=$f_r_state;

	$f_s_zip=JRequest::getInt('f_s_zip',1);

	$arrFields[]='f_s_zip';

	$arrValues[]=$f_s_zip;

	$f_r_zip=JRequest::getInt('f_r_zip',1);

	$arrFields[]='f_r_zip';

	$arrValues[]=$f_r_zip;

	$f_s_country=JRequest::getInt('f_s_country',1);

	$arrFields[]='f_s_country';

	$arrValues[]=$f_s_country;

	$f_r_country=JRequest::getInt('f_r_country',1);

	$arrFields[]='f_r_country';

	$arrValues[]=$f_r_country;

	$f_s_phone=JRequest::getInt('f_s_phone',1);

	$arrFields[]='f_s_phone';

	$arrValues[]=$f_s_phone;

	$f_r_phone=JRequest::getInt('f_r_phone',1);

	$arrFields[]='f_r_phone';

	$arrValues[]=$f_r_phone;

	$m_s_firstname=JRequest::getInt('m_s_firstname',1);

	$arrFields[]='m_s_firstname';

	$arrValues[]=$m_s_firstname;

	$m_r_firstname=JRequest::getInt('m_r_firstname',1);

	$arrFields[]='m_r_firstname';

	$arrValues[]=$m_r_firstname;

	$m_s_lastname=JRequest::getInt('m_s_lastname',1);

	$arrFields[]='m_s_lastname';

	$arrValues[]=$m_s_lastname;

	$m_r_lastname=JRequest::getInt('m_r_lastname',1);

	$arrFields[]='m_r_lastname';

	$arrValues[]=$m_r_lastname;

	$m_s_organization=JRequest::getInt('m_s_organization',1);

	$arrFields[]='m_s_organization';

	$arrValues[]=$m_s_organization;

	$m_r_organization=JRequest::getInt('m_r_organization',1);

	$arrFields[]='m_r_organization';

	$arrValues[]=$m_r_organization;

	$m_s_address=JRequest::getInt('m_s_address',1);

	$arrFields[]='m_s_address';

	$arrValues[]=$m_s_address;

	$m_r_address=JRequest::getInt('m_r_address',1);

	$arrFields[]='m_r_address';

	$arrValues[]=$m_r_address;

	$m_s_city=JRequest::getInt('m_s_city',1);

	$arrFields[]='m_s_city';

	$arrValues[]=$m_s_city;

	$m_r_city=JRequest::getInt('m_r_city',1);

	$arrFields[]='m_r_city';

	$arrValues[]=$m_r_city;

	$m_s_state=JRequest::getInt('m_s_state',1);

	$arrFields[]='m_s_state';

	$arrValues[]=$m_s_state;

	$m_r_state=JRequest::getInt('m_r_state',1);

	$arrFields[]='m_r_state';

	$arrValues[]=$m_r_state;

	$m_s_zip=JRequest::getInt('m_s_zip',1);

	$arrFields[]='m_s_zip';

	$arrValues[]=$m_s_zip;

	$m_r_zip=JRequest::getInt('m_r_zip',1);

	$arrFields[]='m_r_zip';

	$arrValues[]=$m_r_zip;

	$m_s_email=JRequest::getInt('m_s_email',1);

	$arrFields[]='m_s_email';

	$arrValues[]=$m_s_email;

	$m_r_email=JRequest::getInt('m_r_email',1);

	$arrFields[]='m_r_email';

	$arrValues[]=$m_r_email;

	$m_s_country=JRequest::getInt('m_s_country',1);

	$arrFields[]='m_s_country';

	$arrValues[]=$m_s_country;

	$m_r_country=JRequest::getInt('m_r_country',1);

	$arrFields[]='m_r_country';

	$arrValues[]=$m_r_country;

	$m_s_phone=JRequest::getInt('m_s_phone',1);

	$arrFields[]='m_s_phone';

	$arrValues[]=$m_s_phone;

	$m_r_phone=JRequest::getInt('m_r_phone',1);

	$arrFields[]='m_r_phone';

	$arrValues[]=$m_r_phone;

	//Pay later option

	$pay_later_options=JRequest::getVar('pay_later_options','','post','ARRAY');

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

	$arrFields[]='pay_later_options';

	$arrValues[]=$pay_later_options;

	$prevent_duplication=JRequest::getInt('prevent_duplication',0);

	$arrFields[]='prevent_duplication';

	$arrValues[]=$prevent_duplication;

	$godaddy_hosting=JRequest::getInt('godaddy_hosting',0);

	$arrFields[]='godaddy_hosting';

	$arrValues[]=$godaddy_hosting;

	$terms_conditions=JRequest::getInt('terms_conditions',0);

	$arrFields[]='terms_conditions';

	$arrValues[]=$terms_conditions;

	$event_field_width=JRequest::getInt('event_field_width',0);

	$arrFields[]='event_field_width';

	$arrValues[]=$event_field_width;

	$event_date_width=JRequest::getInt('event_date_width',0);

	$arrFields[]='event_date_width';

	$arrValues[]=$event_date_width;
	
	$event_date_show=JRequest::getInt('event_date_show',0);

	$arrFields[]='event_date_show';

	$arrValues[]=$event_date_show;

	$save_payment_info=JRequest::getInt('save_payment_info',0);

	$arrFields[]='save_payment_info';

	$arrValues[]=$save_payment_info;

	$arrFields[]='private_event_msg';

	$arrValues[]=$_REQUEST['private_event_msg'];

	//Get custom fields

	$sql="Select id,name From #__dtregister_fields where published=1 ";

	$database->setQuery($sql);

	$rowCustoms=$database->loadObjectList();

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

	{

		$rowCustom=$rowCustoms[$i];

		$name=$rowCustom->name;

		$value=JRequest::getInt($name,0);

		$arrFields[]=$name;

		$arrValues[]=$value;

	}

	//End of custom fields

	//Insert data into the table

	$sql="TRUNCATE TABLE `#__dtregister_config`  ";

	$database->setQuery($sql);

	$database->query();
    $old_keys = $conf->getJoomfishKeys();
	for($i=0,$n=count($arrFields);$i<$n;$i++)

	{

		$field=$arrFields[$i];

		$value=$arrValues[$i];

		$field=$database->Quote($field);

		$value=$database->Quote($value);

		$sql="Insert Into #__dtregister_config(config_key,config_value,title) Values($field,$value,$field)";

		$database->setQuery($sql);

		if(!$database->query())

			echo $database->getErrorMsg();

	}
    $new_keys = $conf->getJoomfishKeys();
	
	$conf->joomfish_fix();
	
    $task = JRequest::getVar("task");
	
	if($task=="applysettings"){
	  $mainframe->redirect("index2.php?option=$option&task=settings", JText::_( 'SETTINGS_SAVED' ));
	}else{
	  $mainframe->redirect("index2.php?option=$option&task=settings", JText::_( 'SETTINGS_SAVED' ));
	}
	
}

function doexportCSV(){
   global $mosConfig_absolute_path;

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	include("../components/com_dtregister/config.dtregister.php");
	
	$csv_export = new CsvExport();
	
	$exporteventList = $csv_export->getEvents();
	$csv_export->mergeHeader();
	$datefrom = JRequest::getVar('datefrom','');
	$dateto = JRequest::getVar('dateto','');
	$dateto_con = "";
	$datefrom_con = ""; // CAST('2000-01-01' AS DATE)
	if($datefrom!=""){
	   $datefrom = strftime('%Y-%m-%d', strtotime($datefrom)) ." 00:00:00";
	   $datefrom_con = " and a.register_date >= '$datefrom' ";
	}
	
	if($dateto!=""){
	   $dateto = strftime('%Y-%m-%d', strtotime($dateto))." 23:59:59";
	   
	   $dateto_con = " and a.register_date  <= '$dateto' ";
	   
	}
	
	$sql = "select a.* , d.* , e.summary , e.dtstart  , dis.code  from #__dtregister_user a
	        inner join  #__dtregister_group b on a.userId= b.useid
            inner join #__dtregister_group_amount d on d.groupId=b.groupId
			inner join #__jevents_vevdetail As  e on a.eventId=e.evdet_id 
			left join #__dtregister_codes dis on dis.id = a.discount_code_id
			where a.eventId in (".implode(',',$exporteventList).")   $datefrom_con  $dateto_con  
            order by a.register_date desc
			
	       " ;
		   
     $database->setQuery($sql);

    $database->getQuery($sql);

	 $rows = $database->loadObjectList();
     echo $database->getErrorMsg();
	 $csv_rows = array();
	 foreach($rows as $key=>$row){
	    $irow = $csv_export->mapRow($row,'I');
	
		if(count(array_filter((array)$irow))>0){
	    	$csv_rows[] = $irow;
		}
		if($row->userType=='G'){
		    $dt_user = new DT_User($row->userId);
			foreach($dt_user->get_members() as $member){
			   $mrow =  $csv_export->mapRow($member,'G');
			  
			   if(count(array_filter((array)$mrow)) > 0){
			     $csv_rows[] = $mrow ;
			   }
			}
			unset($dt_user);
		}
		
	 }
	
	 $csv_output = implode($csv_separator,$csv_export->getHeader());
	 
	 foreach($csv_rows as $datarow){
	    $results_arr = get_object_vars($datarow);
		$csv_output .= "\n\"".implode ("\"".$csv_separator."\"", $results_arr)."\"";
	 }
	 ob_clean();

	 //die;
	 $csv_export->output($csv_output);
	 
}

function doexportCSV_horizontal(){

	global $mosConfig_absolute_path;

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

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

	$sql="Select distinct eventId From #__dtregister_group_event where export=1";

	$database->setQuery($sql);

	$exportevents=$database->loadAssocList();

	if(is_array($exportevents))

	foreach($exportevents as $value){

		$exporteventList[] = $value['eventId'];

	}

	//Get custom fields here

	 $sql="Select * From #__dtregister_export_fields";

	$database->setQuery($sql);

	$fieldsetting=$database->loadObjectList();

	$group_fields = explode(",",$fieldsetting[0]->group_export_fields);

	$individual_fields = explode(",",$fieldsetting[0]->individual_export_fields);

	$general_export_fields = explode(",",$fieldsetting[0]->general_export_fields);

	$sql="Select * From #__dtregister_fields  where type<>6 and published=1  order by ordering";

	$database->setQuery($sql);

	$rowCustoms=$database->loadObjectList();
    
	if(is_array($individual_fields))

	foreach($individual_fields as $key=>$value){
        if($value=="paid_amount"){
		   $individual_sqlFields[] = "a.".$value ;
		}else{
		   $individual_sqlFields[] = "a.user".ucfirst($value) ;
		}
		
		$group_billing_sqlFields[] = "c.".$value;

		$individual_csvFields[] = ucfirst($value);

		$group_billing_csvFields[] = $value;

	}

	//$sql= "select a.register_date,a.userId,if(a.userType='I','Individual','Group') as userType ,a.userFirstName,a.userLastName,a.userOrganization,a.userAddress,a.userCity,a.userState,a.userCountry,a.userZip,a.userPhone,a.userEmail,e.title";

	  $joomla_user_id_sql = "";

          if(in_array('user_id',$general_export_fields)){

			$joomla_user_id_sql = "  if(a.user_id != 0 , a.user_id ,'' ) user_id," ;

	       }
       
		$sql= "select $joomla_user_id_sql a.register_date, e.summary  ,  e.dtstart publish_up, a.userId " ;

		// if(a.userType='I','Individual','Group') as userType ,".implode(',',$individual_sqlFields)." ";

		//if(in_array('userType',$general_export_fields)){

			$sql .= " , if(a.userType='I','Individual','Group') as userType " ;

		//}

		$sql .= ",".implode(',',$individual_sqlFields)." " ;

	//Here will be custom fields data

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

	{

		$rowCustom=$rowCustoms[$i];

		if($rowCustom->export_individual){

			$sql.=",a.".$rowCustom->name;

		}

	}

	//End custom fields

	//Include all members data

	//if(in_array('groupId',$group_fields)){

		$sql.=",b.groupId";

	//}

	$sql.=",c.groupMemberId,c.groupUserId";
	
	if(in_array('title',$group_fields))

	{

		$sql.=",c.title";

	}

	if(in_array('firstname',$group_fields))

	{

		$sql.=",c.firstname";

	}

	if(in_array('lastname',$group_fields))

	{

		$sql.=",c.lastname";

	}

	if( in_array('organization',$group_fields))

	{

		$sql.=",c.organization";

	}

	if( in_array('address',$group_fields))

	{

		$sql.=",c.address";

	}
	
	if(in_array('address2',$group_fields))

	{

		$sql.=",c.address2";

	}

	if(in_array('city',$group_fields))

	{

		$sql.=",c.city";

	}

	if( in_array('state',$group_fields))

	{

		$sql.=",c.state";

	}

	if( in_array('country',$group_fields))

	{

		$sql.=",c.country";

	}

	if( in_array('zip',$group_fields))

	{

		$sql.=",c.zip";

	}

	if( in_array('email',$group_fields))

	{

		$sql.=",c.email";

	}

	if( in_array('phone',$group_fields))

	{

		$sql.=",c.phone";

	}

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

	{

		$rowCustom=$rowCustoms[$i];

		$name=$rowCustom->name;

		if($rowCustom->export_group)

		{

			$sql.=",c.$name as m_$name";

		}

	}

	if(in_array('numberOfPerson',$general_export_fields)){

		$sql.=", d.numberOfPerson";

	}

	if(in_array('amount',$general_export_fields)){

			$sql .= " ,d.amount " ;

	 }

	 if(in_array('payment_type',$general_export_fields)){

			$sql .= " ,payment_type " ;

	 }

	 if(in_array('paid',$general_export_fields)){

			$sql .= ",if(pay_later_paid=1 ,'Paid', if(payment_type!='Free' && payment_type!='','Not Paid',' ')) as paid " ;

	 }

	 if(in_array('confirmNum',$general_export_fields)){

			$sql .= " ,a.confirmNum " ;

	 }

	  if(in_array('code',$general_export_fields)){

			$sql .= " ,dis.code " ;

	 }
     $datefrom = JRequest::getVar('datefrom','');
	$dateto = JRequest::getVar('dateto','');
	$dateto_con = "";
	$datefrom_con = ""; // CAST('2000-01-01' AS DATE)
	if($datefrom!=""){
	   $datefrom = strftime('%Y-%m-%d', strtotime($datefrom)) ." 00:00:00";
	   $datefrom_con = " and a.register_date > '$datefrom' ";
	}
	
	if($dateto!=""){
	   $dateto = strftime('%Y-%m-%d', strtotime($dateto))." 00:00:00";
	   
	   $dateto_con = " and a.register_date  < '$dateto' ";
	   
	}
 	echo"<pre>" .$sql.=" , a.eventId 

 from #__dtregister_user a

inner join  #__dtregister_group b on a.userId= b.useid

left join  #__dtregister_group_member c on b.groupId=c.groupUserId

inner join #__dtregister_group_amount d on d.groupId=b.groupId

inner join #__jevents_vevdetail As  e on a.eventId=e.evdet_id

left join #__dtregister_codes dis on dis.id = a.discount_code_id

 where a.eventId in (".implode(',',$exporteventList).") and a.payment_verified=1   $datefrom_con  $dateto_con  

order by a.register_date desc

";

	$database->setQuery($sql);

echo $database->getQuery($sql);

	$rows = $database->loadObjectList();
   echo $database->getErrorMsg();
	print_R($rows);

	$prev_group  = 0;

//die;

$temp_rows = array();
ob_clean();
	foreach($rows as $key=>$row){

		$row->publish_up = get_date($row->publish_up);

        $row->amount = numberFormat($row->amount,2);

		if($row->userType=='Group' && $prev_group != $row->groupId ){

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

				if(!isset($row->$value)){

					//continue ;
					$row->$value = " ";

				}

				if($value == 'user_id')

				$first_row->$value = $row->$value;

			}

			$first_row->register_date = $row->register_date;

			$first_row->eventname = $row->summary;
            
			 if(in_array('category',$general_export_fields)){

					$dt_evt = new Event($row->eventId);
					 $category = new mosDtCategory($database) ;
					 
					 $category->load($dt_evt->category);
					
                     $first_row->category = $category->categoryName;
			       
		      }
			  if(in_array('location',$general_export_fields)){

					 $dt_evt = new Event($row->eventId);
					 				 
					 $location = $dt_evt->get_location();
					
                     $first_row->location  = $location->name;
			       
		      }
			
			$first_row->publish_up = $row->publish_up;

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

				if(!isset($row->$value)){
                    
					$row->$value = " "; 
					//continue ;

				}

				if($value == 'userType')

				$first_row->$value = $row->$value;

			}

			$first_row->userId = $row->userId;

			/*$second_row->register_date = $row->register_date;

			$second_row->title = $row->title;

			$second_row->publish_up = $row->publish_up;

			$second_row->userId = $row->userId;*/

			foreach($individual_fields as $key=>$value){
                if($value=="paid_amount"){
				   $first_row->$value = $row->{$value};
				}else{
				   $first_row->$value = $row->{'user'.ucfirst($value)};
				}
				
			}

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

				if(!isset($row->$value)){

					if($value == 'code'){

						$row->$value = "  ";

					}else{
                        $row->$value = " ";
						//continue ;

					}

				}

				if($value != 'userType' && $value != 'user_id')
                 if(!isset($first_row->$value))
				$first_row->$value = $row->$value;

			}

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

				if(!isset($row->$value)){

					$second_row->$value = " ";
					continue ;

				}

				if($value =="groupId" && in_array('groupId',$group_fields)){

					$second_row->$value = $row->$value;

				}elseif($value !="groupId"){

					$second_row->$value = $row->$value;

				}

			}

			foreach($rowCustoms as $custom){

				if($custom->export_individual){

					$first_row->{$custom->name} = $row->{$custom->name};

				}

				if($custom->export_group){

					$second_row->{$custom->name} = $row->{'m_'.$custom->name};

				}

			}

			//$first_row->groupMemberId = $row->groupMemberId;

			//$first_row->groupUserId = $row->groupUserId;

			$temp_rows[$row->userId] = $first_row;

            if(isset($second_row))

			$temp_rows[$row->userId]->groups[] = $second_row;

			$groupUser_count[$row->userId] = 1;

			//$temp_rows[] = $second_row;

			$prev_group = $row->groupId;

			unset($first_row);

			unset($second_row);

		}elseif($row->userType=='Group' && $prev_group==$row->groupId){

		//	$second_row->register_date = $row->register_date;

			//$second_row->title = $row->title;

			//$second_row->publish_up = $row->publish_up;

			//$second_row->userId = $row->userId;

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

				if(!isset($row->$value)){

                    $second_row->$value = " ";
					continue ;

				}

				$second_row->$value = $row->$value;

			}

			foreach($rowCustoms as $custom){

				if($custom->export_group){

					$second_row->{$custom->name} = $row->{'m_'.$custom->name};

				}

			}
            echo "<pre>";
			print_r($second_row);
			print_r($group_fields);
			
			//die;
			$temp_rows[$row->userId]->groups[] = $second_row;

			$groupUser_count[$row->userId] += 1;

			//$temp_rows[] = $second_row;

			unset($second_row);

		}elseif($row->userType=='Individual'){

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

				if(!isset($row->$value)){

					continue ;

				}

				if($value == 'user_id')

				$first_row->$value = $row->$value;

			}

			$first_row->register_date = $row->register_date;

			$first_row->eventname = $row->summary;
             if(in_array('category',$general_export_fields)){

					$dt_evt = new Event($row->eventId);
					 $category = new mosDtCategory($database) ;
					 
					 $category->load($dt_evt->category);
					
                     $first_row->category = $category->categoryName;
			       
		      }
			 if(in_array('location',$general_export_fields)){

					 $dt_evt = new Event($row->eventId);
					 				 
					 $location = $dt_evt->get_location();
					 
                     $first_row->location  = $location->name;
					
		      }
			$first_row->publish_up = $row->publish_up;
	
			foreach($general_export_fields as $key=>$value){

				if(!isset($row->$value)){

					if($value == 'code'){

						$row->$value = "  ";

					}else{
                          
						continue ;

					}

					continue ;

				}

				if($value == 'userType')

				$first_row->$value = $row->$value;

			}
           
			$first_row->userId = $row->userId;

			foreach($individual_fields as $key=>$value){
                 if($value=="paid_amount"){
				   $first_row->$value = $row->{$value};
				}else{
				   $first_row->$value = $row->{'user'.ucfirst($value)};
				}
				
			}
           global $lang_var ; 
			
			foreach($general_export_fields as $key=>$value){

				if(!isset($row->$value)){

					if($value == 'code'){

						$row->$value = "  ";

					}else{
                         $row->$value = " ";
						//continue ;

					}

					//continue ;

				}
				
				if($value != 'userType' && $value !='user_id'){

					if($value == '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];

						}

						$first_row->$value = $lang_var[$row->payment_type];

					}else{
                        if(!isset($first_row->$value))
						$first_row->$value = $row->$value;

					}

				}

			}
	foreach($rowCustoms as $custom){

				if($custom->export_individual){

					$first_row->{$custom->name} = $row->{$custom->name};

				}

			}

			//$first_row->groupMemberId = $row->groupMemberId;

			//$first_row->groupUserId = $row->groupUserId;
            
			$temp_rows[] = $first_row;

			unset($first_row);

		}

	}

	//ob_clean();

	//print_R($rows);

// echo "<pre>";

	//print_R($groupUser_count);

    //die;

	unset($rows);

	$rows = $temp_rows;

	unset($temp_rows);

	//print_R($rows);

	 sort($groupUser_count);

	$max_group_count = @end($groupUser_count);

	//echo "</pre>";

	//die;

//ob_clean();
   
	if(count($rows)){

		$results_arr=array();

		$csv_output = "";

        if(in_array('user_id',$general_export_fields)){

			$csv_output .="Joomla UserId ,";

			unset($general_export_fields[array_search('user_id', $general_export_fields)]);

		}
      
		$csv_output .= "Register date,Event name,";
		
		 if(in_array('category',$general_export_fields)){

			$csv_output .="Category,";

			unset($general_export_fields[array_search('category', $general_export_fields)]);

		}
		
		if(in_array('location',$general_export_fields)){

			$csv_output .="Location,";

			unset($general_export_fields[array_search('location', $general_export_fields)]);

		}
		
		 $csv_output .= "Event date,";
	
		if(in_array('userType',$general_export_fields)){

			$csv_output .="userType,";

			unset($general_export_fields[0]);

		}

		$csv_output .="DT UserId,".implode(",",array_filter($individual_csvFields))."";
		
		$csv_output .= count(array_filter($general_export_fields))>0?", ".implode(",",array_filter($general_export_fields)):'' ;

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

		{

			$rowCustom=$rowCustoms[$i];

			if($rowCustom->export_individual){

				$csv_output.=",".$rowCustom->name;

			}

		}

		//$csv_output.=",groupMemberId,groupUserId";

		//max_group_count;

		for($i=1;$i<=$max_group_count;$i++){

			foreach($group_fields as $group_field){

				$groupMemberHeader[] = "M$i $group_field";

			}

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

			{

				$rowCustom=$rowCustoms[$j];

				$name=$rowCustom->name;

				if($rowCustom->export_group)

				{

					$groupMemberHeader[] = "M$i $rowCustom->name";

				}

			}

		}

		echo $csv_output.= ",".implode(",",$groupMemberHeader);
		
		foreach($rows as $r) {

			$results_arr = get_object_vars($r);

			$results_arr['register_date']=get_date($results_arr['register_date']);
            echo "<pre>";
			print_r($results_arr['groups']);
			if(isset($results_arr['groups'])){
			
			}
			if(isset($results_arr['groups'])){

				$groups = $results_arr['groups'];

				unset($results_arr['groups']);

				foreach($groups as $group){

				  $group_vars = get_object_vars($group);

					$groupCsvRow[]= implode('","',$group_vars);

				}

				unset($groups);
               
				$groupCsvRow = implode('","',$groupCsvRow);
				
				//die;

			}

			$csv_output .= "\n\"".implode ("\",\"", $results_arr)."\"";

			if($groupCsvRow !=""){

				$csv_output .= ',"'.$groupCsvRow.'"';
               // die;
			}

			unset($groupCsvRow);

			$polltitle= $results_arr['ID'];

		}

		$csv_output .= "\n";
      
		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";

			@ob_end_clean();

			ob_start();

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

	}

}

//Custom fields function here

function showCustomFields( $option )

{

	global $mainframe;

	jimport('joomla.html.pagination');

	$listLimit = $mainframe->getCfg( 'list_limit', 10 );

	$database = &JFactory::getDBO();

	$limit 		= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $listLimit ) );

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

	$limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );

	$search 	= $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );

	if (get_magic_quotes_gpc()) {

		$search	= stripslashes( $search );

	}

	$where = array();

	if ($search) {

		$where[] = "LOWER(a.name) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";

	}

	// get the total number of records

	$query = "SELECT COUNT(*)"

	. "\n FROM #__dtregister_fields AS a"

	. (count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : "")

	;

	$database->setQuery( $query );

	$total = $database->loadResult();

	$pageNav = new JPagination( $total, $limitstart, $limit  );

	$query = "Select * From #__dtregister_fields As a " ;

	if(count($where))

	{

		$query.=" Where ".implode(" AND ",$where);

	}

	$query.=" order by a.ordering ";

	$database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );

	$rows = $database->loadObjectList();

	if ($database->getErrorNum()) {

		echo $database->stderr();

		return false;

	}

	HTML_groups::showCustomFields($option, $rows , $search, $pageNav );

}

function editCustomfield($option, $id)

{

	$database = &JFactory::getDBO();

	$row = new mosField( $database );
	
	// load the row from the db table

	$row->load( (int)$id );
$field =  new Custom_field($row->id);
	//Published

	if(!$id)

	{

		$row->published=1;

		$row->required=0;

	}
	if(isset($_POST['name'])){
	   $row->bind( $_POST );
	}
	
	//Added to suport multi field types

	//Get field types
   $list = $field->parent_list();
   $parent_option =  array();
   
    $parent_option[]=JHTML::_('select.option','',JText::_('DT_SELECT_FIELD'));
   foreach($list as $key=>$value){
       $parent_option[]=JHTML::_('select.option',$key,$value);
   }
	
	$lists =  array();
	$lists["parent_list"]=JHTML::_('select.genericlist', $parent_option,"parent_id","","value","text",$row->parent_id);
	$fieldTypes=array();
    $parent_type =  array(1,3,4);
	/*if($field->hasChild()){
	   
	   $fieldTypes[]=JHTML::_('select.option',"1","Dropdown");
	   $fieldTypes[]=JHTML::_('select.option',"3","Checkbox");
	
	   $fieldTypes[]=JHTML::_('select.option',"4","Radio");
	      
	}else{*/
	    $fieldTypes[]=JHTML::_('select.option',"0","Text");
    
		$fieldTypes[]=JHTML::_('select.option',"1","Dropdown");
	
		$fieldTypes[]=JHTML::_('select.option',"2","Texarea");
	
		$fieldTypes[]=JHTML::_('select.option',"3","Checkbox");
	
		$fieldTypes[]=JHTML::_('select.option',"4","Radio");
	
		$fieldTypes[]=JHTML::_('select.option',"5","Date");
	
		$fieldTypes[]=JHTML::_('select.option',"6","Textual");
		
		$fieldTypes[]=JHTML::_('select.option',"7","Upload");
	
	//}
	
	//$fieldTypes[]=JHTML::_('select.option',"8","Hidden");
	
	$lists["type"]=JHTML::_('select.genericlist', $fieldTypes,"type","onchange='changeFieldType(1);'","value","text",$row->type);

	//End added

	//New list

	if($row->type<3){

		$atttribute=' disabled=true ';

	} else {$atttribute='';}

	if($row->new_line==null)

		$row->new_line=0;

	$lists['new_line']=JHTMLSelect::booleanlist('new_line',$atttribute,$row->new_line);

	$lists['published']=JHTMLSelect::booleanlist('published',$atttribute,$row->published);
	
	$lists['hidden']=JHTMLSelect::booleanlist('hidden',$atttribute,$row->hidden);

	$lists['required']=JHTMLSelect::booleanlist('required',$atttribute,$row->required);
	
	$lists['allevent']=JHTMLSelect::booleanlist('allevent',$atttribute,$row->allevent);
   
	 $options = array();
   
   $options[]=JHTML::_('select.option',"0",JText::_( 'DT_NONE' ));
   $options[]=JHTML::_('select.option',"1",JText::_( 'DT_INDIVIDUAL' ));
   $options[]=JHTML::_('select.option',"2",JText::_( 'DT_GROUP' ));
   $options[]=JHTML::_('select.option',"3",JText::_( 'DT_BOTH'));
	$lists["showed"]=JHTML::_('select.radiolist', $options,"showed","","value","text",$row->showed);
   
   $options = array();
   
   $options[]=JHTML::_('select.option',"1",JText::_( 'DT_EACH_MEMBER' ));
   $options[]=JHTML::_('select.option',"2",JText::_( 'DT_BILLING_ONLY' ));
   $options[]=JHTML::_('select.option',"3",JText::_( 'DT_MEMBERS_BILLING'));
   
   $lists["group_behave"]=JHTML::_('select.radiolist', $options,"group_behave","","value","text",$row->group_behave);
   
	HTML_groups::editCustomfield($row, $option,$lists);

}

function saveCustomfield( $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	$row = new mosField( $database );

	$id=JRequest::getInt('id',0);

	if($id){
	
	  $row->load($id);
	  
	}else{
	   $name=JRequest::getVar('name','');
	   $query = "Select * from #__dtregister_fields where name = '$name'" ;
	   $database->setQuery($query);
	   $database->query();
	   $num_rows = $database->getNumRows();
	   
	   if($num_rows > 0){
	      
		  editCustomfield($option,0);
		  return ;
	   }

	}
	if(!isset($_POST['parent_id'])){
	    $_POST['parent_id'] = NULL ;
	}
	if(!isset($_POST['selection_values'])){
	    $_POST['selection_values'] = "" ;
	}
    $_POST['label'] = html_entity_decode($_POST['label']);
	if (!$row->bind( $_POST )) {

		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";

		exit();

	}

	if (!$row->check()) {

		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";

		exit();

	}

	//Store record

    $row->values = html_entity_decode(stripslashes($row->values),null,'UTF-8');
	$row->selection_values = stripslashes(implode(",",$row->selection_values));
	$row->description = html_entity_decode(stripslashes($row->description));
	$row->label = html_entity_decode($row->label,null,'UTF-8');
	$row->selected =html_entity_decode($row->selected,null,'UTF-8');
	$row->textual =html_entity_decode($row->textual,null,'UTF-8');
	
	if (!$row->store()) {

		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";

		exit();

	}
    if($row->allevent == 1){
	   
	   $row->enableALLEvents();
	}

	if(!$id)

	{

		$row->ordering=$row->id;

		$row->store();

		//Add new field to #__dtregister_user table

		$sql="ALTER TABLE `#__dtregister_user` ADD `$row->name` text NULL ;";

		$database->setQuery($sql);

		$database->query();

		//Add this field to #__dtregister_group

		$sql="ALTER TABLE `#__dtregister_group_member` ADD `$row->name` text NULL ;";

		$database->setQuery($sql);

		$database->query();

		//Okie, done

	}

	$mainframe->redirect( "index2.php?option=$option&task=custom_fields" );

}

function removeCustomfield( $cid, $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	if (!is_array( $cid ) || count( $cid ) < 1) {

		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";

		exit;

	}

	$row=new mosField($database);

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

	{

		$id=$cid[$i];

		$row->load($id);

		//Drop the new column

		$sql="ALTER TABLE `#__dtregister_user` DROP `$row->name`;";

		$database->setQuery($sql);

		$database->query();

		//Drop this field from #__dtregister_user

		$sql="ALTER TABLE `#__dtregister_group_member` DROP `$row->name`;";

		$database->setQuery($sql);

		$database->query();

		//Drop from field event table

		$sql="Delete From #__dtregister_field_event Where field_id=$id";

		$database->setQuery($sql);

		$database->query();

		//Delete this field

		$row->delete();

	}

	$mainframe->redirect( "index2.php?option=$option&task=custom_fields" );

}

/**

* Publishes or Unpublishes one or more records

* @param array An array of unique category id numbers

* @param integer 0 if unpublishing, 1 if publishing

* @param string The current url option

*/

function publishCustomfield( $cid=null, $publish=1,  $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	if (!is_array( $cid ) || count( $cid ) < 1) {

		$action = $publish ? 'publish' : 'unpublish';

		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";

		exit;

	}

	JArrayHelper::toInteger( $cid );

	$cids = 'id=' . implode( ' OR id=', $cid );

	$query = "UPDATE #__dtregister_fields"

	. "\n SET published = " . (int) $publish

	. "\n WHERE ( $cids )"

	;

	$database->setQuery( $query );

	if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

		exit();

	}

	$mainframe->redirect( "index2.php?option=$option&task=custom_fields" );

}

function publishEvent( $cid=null, $publish=1,  $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	if (!is_array( $cid ) || count( $cid ) < 1) {

		$action = $publish ? 'publish' : 'unpublish';

		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";

		exit;

	}

	JArrayHelper::toInteger( $cid );

   foreach($cid as $slab_id){

	  $query = "select eventId from #__dtregister_group_event where slabId='$slab_id'";

	  $database->setQuery( $query );

	  $eventId = $database->loadResult();

	  $dt_evt = new Event($eventId);

	  $dt_evt->save_field('publish',$publish);

   }
       unset($_REQUEST['task']);
	
	$_REQUEST['act'] = 'groups';
	
    $get_str = http_build_query($_REQUEST);

         $mainframe->redirect("index2.php?".$get_str);
	$mainframe->redirect( "index.php?option=com_dtregister&act=groups" );

}

function archiveEvent( $cid=null, $archive=1,  $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	if (!is_array( $cid ) || count( $cid ) < 1) {

		$action = $archive ? 'archive' : 'archive';

		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";

		exit;

	}

	JArrayHelper::toInteger( $cid );

   foreach($cid as $slab_id){

	  $query = "select eventId from #__dtregister_group_event where slabId='$slab_id'";

	  $database->setQuery( $query );

	  $eventId = $database->loadResult();

	  $dt_evt = new Event($eventId);

	  $dt_evt->save_field('archive',$archive);

   }
     unset($_REQUEST['task']);
	
	$_REQUEST['act'] = 'groups';
	
    $get_str = http_build_query($_REQUEST);

         $mainframe->redirect("index2.php?".$get_str);
	$mainframe->redirect( "index.php?option=com_dtregister&act=groups" );

}
/**

* Moves the order of a record

* @param integer The increment to reorder by

*/

function orderCustomfield( $uid, $inc, $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	$row = new mosField( $database );

	$row->load( (int)$uid );

	$row->reorder();

	$row->move( $inc, true );

	//$row->updateOrder();

	$mainframe->redirect( "index2.php?option=$option&task=custom_fields" );

}

function cancelCustomfield( $option ) {

	global $mainframe;

	$mainframe->redirect( "index2.php?option=$option&task=custom_fields" );

}

function saveOrderCustomfield($option,$cid)

{

	global $mainframe;

	$database = &JFactory::getDBO();

	$order	= JRequest::getVar( 'order', array(0), '', 'array' );

	$total		= count( $cid );

	$row 		= new mosField( $database );

	// update ordering values

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

		$row->load( (int) $cid[$i] );

		if ($row->ordering != $order[$i]) {

			$row->ordering = $order[$i];

			if (!$row->store()) {

				echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

				exit();

			}

		}

	}

	$mainframe->redirect("index2.php?option=$option&task=custom_fields");

}

function showEventWaiting($option) {

	global $displaytime ,$option ,$mainframe ;

	jimport('joomla.html.pagination');

	jimport('joomla.html.select');
    
	$order_Dir = Jrequest::getVar('filter_order_Dir','asc');
	$order     = Jrequest::getVar('filter_order','name');
    
	if($order == "name"){
	   $order = "fname $order_Dir , lname  ";
	}
	
	$listLimit = $mainframe->getCfg( 'list_limit', 10 );

	$database = &JFactory::getDBO();

	$limit = JRequest::getInt('limit', $listLimit);

	$limitstart = JRequest::getInt('limitstart', 0);

	$eventId=JRequest::getInt('event_id',0);

	$where=array();

	if($eventId)

	{

		$where[]=" a.event_id=$eventId ";

	}

	$sql =	"SELECT COUNT(a.id)"

	.	"\n FROM #__dtregister_waiting AS a"

	.(count( $where ) ? " Where ".implode(" AND ",$where):"")

	.	"\n ORDER BY $order $order_Dir"

	;

	$database->setQuery($sql);
    
	$total = $database->loadResult();

	// require_once(JPATH_COMPONENT.DS.'includes/pageNavigation.php');

	$pageNav = new JPagination ($total, $limitstart, $limit);

	$sql =	"SELECT a.*,b.summary , b.dtstart , b.dtend  FROM #__dtregister_waiting As a

			Inner Join #__jevents_vevdetail as b

			On a.event_id=b.evdet_id

		"

	.( count($where)? " Where ".implode(" AND ",$where):"")
   
	.	"\n ORDER BY $order $order_Dir"

	;

	$database->setQuery($sql, $pageNav->limitstart, $pageNav->limit);
    $rows = $database->loadObjectList();

	//Get the event list

	$sql="SELECT evdet_id ,summary , dtstart , dtend FROM #__jevents_vevdetail order by dtstart desc ";

	if ($eventId){$sql .= " WHERE evdet_id='".$eventId."'";}

	$database->setQuery($sql);

	$rowEvents=$database->loadObjectList();

	$arrEvents=array();

	$options[]=JHTML::_('select.option',"Select event",'',"title",'id');

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

	{

		$rowEvent=$rowEvents[$i];

		$options[]=JHTML::_('select.option',$rowEvent->summary." (".get_date($rowEvent->dtstart,$rowEvent->dtend).")",$rowEvent->evdet_id,'title','id');

	}

	$lists["event_list"]=JHTML::_('select.genericlist', $options,'event_id',"onchange=submit()","id","title",$eventId);

	HTML_groups::showEventWaiting($rows, $pageNav,$option,$lists);

}

function viewEventWaiting($option, $id) {

	$database = &JFactory::getDBO();

	$sql =	"SELECT a.*, b.summary"

	.	"\n FROM #__dtregister_waiting AS a"

	.	"\n INNER JOIN #__jevents_vevdetail AS b ON a.event_id=b.evdet_id"

	.	"\n WHERE a.id=$id"

	;

	$database->setQuery($sql);

	$row = $database->loadObject();

	HTML_groups::viewEventWaiting($row, $option);

}

function removeEventWaiting($option, $cid) {

	global $mainframe;

	$database = &JFactory::getDBO();

	if (!is_array($cid) || count($cid) < 1) {

		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";

		exit;

	}

	if (count($cid)) {

		 JArrayHelper::toInteger($cid);

		$cids = 'id=' . implode(' OR id=', $cid);

		$sql =	"DELETE FROM #__dtregister_waiting WHERE ($cids)"

		;

		$database->setQuery($sql);

		$database->query();

	}

	if(class_exists("JConfig")){

		$mainframe->redirect("index.php?option=$option&act=full_event");

	} else {

		$mainframe->redirect("index2.php?option=$option&act=full_event");

	}

}

class mosEventWaiting extends JTable {

	var $id							= null;

	var $event_id					= null;

	var $fname						= null;

	var $lname						= null;

	var $phone						= null;

	var $email						= null;

	var $address					= null;

	var $state						= null;

	var $country					= null;

	var $zip						= null;

	var $number_registrats			= null;

	function mosEventWaiting(&$db) {

		$this->JTable('#__dtregister_waiting', 'id', $db);

	}

}

function newMember($option){

	$database = &JFactory::getDBO();

	include(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'config.dtregister.php');

	$eventId=JRequest::getInt('event_id',0);

	$userId=JRequest::getInt('user_id',0);
    
	$dt_event = new Event($eventId);
	//Get list of users

	$sql="Select * From #__users order by name";

	$database->setQuery($sql);

	$rowUsers=$database->loadObjectList();

	$options=array();

	$options[]=JHTML::_('select.option',"0","Select user","id","username");

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

		$options[]=JHTML::_('select.option',$rowUsers[$i]->id,$rowUsers[$i]->name." (".$rowUsers[$i]->username.")",'id','username');

	}

	#$rowUsers=array_merge($options,$rowUsers);

	$lists["user_list"]=JHTML::_('select.genericlist', $options,"user_id"," onchange=document.adminForm.submit(); ","id","username",$userId);

	if(($userId>0) && $cb_integrated)

	{

		//Get the user detail

		$sql="Select a.id,a.email,b.*

			From #__users As a

			Inner Join #__comprofiler As b

			On a.id=b.user_id

			Where a.id=$userId

			";

		$database->setQuery($sql);

		$rowProfile = $database->loadObject();

	}

	else

	{

		$rowProfile=null;

	}
	
	$options=array();

	$options[]=JHTML::_('select.option', '','Select payment method');

	$options[]=JHTML::_('select.option', 'Authorize.net',JText::_('AUTH_NET'));
    $options[]=JHTML::_('select.option', 'Echeck',JText::_('ECHECK'));
	$options[]=JHTML::_('select.option', 'GoogleCheckout', JText::_( 'DT_GOOGLE_CHECKOUT' ));
	
	$options[]=JHTML::_('select.option', 'PayPal',JText::_('PAYPAL'));
   $options[]=JHTML::_('select.option', 'Eway', JText::_( 'DT_EWAY' ));
	$options[]=JHTML::_('select.option', 'ideal',JText::_('DT_PAY_IDEAL'));
   $options[]=JHTML::_('select.option', 'idealRabo', JText::_( 'DT_PAY_IDEAL_LITE' ));
	$options[]=JHTML::_('select.option', 'NetDeposit', JText::_( 'DT_NETDEPOSIT' ));
	$options[]=JHTML::_('select.option', 'Mail',JText::_('DT_MAILIN_PAYMENT'));

	$options[]=JHTML::_('select.option', 'Phone',JText::_('DT_CALLIN_PAYMENT'));

	$options[]=JHTML::_('select.option', 'At_door',JText::_('DT_PAY_AT_DOOR'));
   
	$lists["payment_type"]=JHTML::_('select.genericlist', $options,'payment_type','','value','text','');

	$lists["pay_later_paid"]=JHTMLSelect::booleanlist("pay_later_paid","",0);
   
	$titles = explode("|",$titleoptions);
	$temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

	foreach($titles as $title){
	
		$temp[] = JHTML::_('select.option', $title, $title);
	
	}
	        
	$titles = $temp;
			
    $lists["titles"] = JHTML::_('select.genericlist',$temp,'title', 'class="inputbox" size="1"', 'value', 'text');
	HTML_groups::newMember($option,$eventId,$lists,$rowProfile,$dt_event); 

}

function saveNewMember($option)

{

	global $mainframe;
    include(JPATH_SITE."/components/com_dtregister/config.dtregister.php");
	$database = &JFactory::getDBO();

	$eventId=JRequest::getInt('event_id',0);

	$userId=JRequest::getInt('user_id',0);
    
	$title=JRequest::getString('title','');
	
	$firstName=JRequest::getString('firstname','');

	$lastName=JRequest::getString('lastname','');

	$organization=JRequest::getString('organization','');

	$address=JRequest::getString('address','');
	
	$address2=JRequest::getString('address2','');

	$city=JRequest::getString('city','');

	$state=JRequest::getString('state','');

	$country=JRequest::getString('country','');

	$zip=JRequest::getString('zip','');

	$phone=JRequest::getString('phone','');

	$email=JRequest::getString('email','');

	$paymentType=JRequest::getString('payment_type','');

	//Calculate event amount here

	$dt_evt =  new Event($eventId);
	
	$amount =  $dt_evt->get_fee(1,$userId); 
	
	 $fld = new Custom_field();
			$fields=array() ;
			
            $fld->getAllFields($eventId,'I',true,0,$fields) ;
			
			$rows = $fields ;
			foreach($rows as $field){
			   $field->field_id = $field->id ;
			}

	$arrFieldIds=array();

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

	{

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

	}

	if(count($arrFieldIds))

	{

		$rowCustoms=$rows ;

	}

	else

	{

		$rowCustoms=null;

	}

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

	{
       
		$rowCustom=$rowCustoms[$i];
          if(!$rowCustom->fee_field){
		   continue ;
		}
		$name=$rowCustom->name;

		$customType=$rowCustom->type;

		$values=$rowCustom->values;

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

		$fees=$rowCustom->fees;

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

		$postedValue=JRequest::getVar($name,'');

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

		{

			if($customType==3)

			{

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

				{

					$amount+=$arrFees[$j];

				}

			}else if($customType == 2){
				
				$amount+= getTextareaFee(strlen(stripslashes($postedValue)),$rowCustom->textareafee);
				
			
			}else

			{

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

				{

					$amount+=$arrFees[$j];

					break;

				}

			}

		}

	}

	//Insert data into users table

	$memtot=1;
   
	$pay_later_paid=JRequest::getVar('pay_later_paid');

	if(($paymentType !='Authorize.net') && ($paymentType !='Authorize.net') && ($paymentType !='Authorize.net'))

	{

		//Change it to pay later

		switch ($paymentType)

		{

			case "Mail-in Payment":

				$payLaterOption=2;

				break;

			case "Phone Payment":

				$payLaterOption=3;

				break;

			case "At The Door":

				$payLaterOption=1;

				break;

			default:

				$payLaterOption=1;

				break;

		}

		//$paymentType="Pay Later";

	}else{
	   
	   $pay_later_paid = 1 ;
	   	
	}

	$chars = "0123456789";

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

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

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

   		}
        $user = new DT_User();
		$confirmNum = $user->generateconfirmNum();

		if ($amount > 0){

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

				

				$user->eventId = $eventId;

				$valid = $user->validate_code(JRequest::getString('discount_code',''));

				if($valid){

					$user->set_discount_code(JRequest::getString('discount_code',''));

					$dt_code = new DiscountCode($user->discount_id);

					$discount_code_amount = $dt_code->get_discount_amount($amount);

					$_SESSION['register']['discount_code_id'] = $user->discount_id;

					$amount -= $discount_code_amount ;

				}

			}

	//Insert data here

   if($amount == 0){

		 $paymentType = "Free";

   }
   $sql="INSERT into #__dtregister_user (eventId, userType, userTitle, userFirstName, userLastName, userOrganization, userAddress,userAddress2, userCity, userState,userCountry,userZip,userPhone,

	  userEmail,register_date,payment_type,user_id,pay_later_option,pay_later_paid,confirmNum,discount_code_id,paid_amount) values($eventId,'I',".$database->Quote($title).",".$database->Quote($firstName).",".$database->Quote($lastName).", ".$database->Quote($organization)." ,".$database->Quote($address).", ".$database->Quote($address2).",'$city','$state','$country','$zip','$phone','$email',now(),'$paymentType','$userId','$payLaterOption','$pay_later_paid','$confirmNum','".$user->discount_id."',".$database->Quote($_REQUEST['paid_amount']).")";

	 $database->setQuery($sql);
 $paid_amount =  $_REQUEST['paid_amount'] ;
	if (!$database->query()) {

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

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

		die();

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

	}

	$userId=$database->insertid();
	if($barcode_enable){
       $test = new DTbarcode($confirmNum,$confirmNum);
       $test->preview();
	}
	//Update custom fields value

     $fld = new Custom_field();
			$fields=array() ;
			
            $fld->getAllFields($eventId,'I',true,0,$fields) ;
			
			$rows = $fields ;
			foreach($rows  as $field){
			   $field->field_id = $field->id ;
			}
	
	$arrFieldIds=array();

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

	{

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

	}

	if(count($arrFieldIds))

	{

		$rowCustoms =  $rows ;

	}

	//Get custom fields value here

	if(count($rowCustoms))

	{

		$arrFields=array();

		$arrValues=array();

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

		{

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$arrFields[]=$name;

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

			if($rowCustom->type==3)

			{

				if(is_array($value))

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

			}

			$arrValues[]=$value;

		}

	}

	if(count($arrFields)>0)

	{

		//Update data

		$sql="Update #__dtregister_user Set ";

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

		{

			$name=$arrFields[$i];

			$value=$arrValues[$i];

			if($i<($n-1))

			{

				$sql.=" $name=".$database->Quote($value).",";

			}

			else

			{

				$sql.=" $name='$value' ";

			}

		}

		echo "<br />".$sql.=" Where userId=".$userId;
     
		$database->setQuery($sql);

		if(!$database->query())

		{

			echo "Error:". $database->getErrorMsg();

			die();

		}

	}

	//End if

	 $sql="insert into #__dtregister_group(useid) values($userId)";

	 $database->setQuery($sql);

	 $database->query();

	 $gid=$database->insertid();
     $dt_event =  new Event($eventId);
	 $amount += $dt_event->getTaxAmount($amount);
	  if($paid_amount<$amount){
	    $cancel = $partial_default_status ;
	 }else{
	    $cancel = $paid_default_status ;
	 }
	 
	 if(in_array($paymentType,array('At_door','Mail','Phone'))){
	    $cancel = $paylater_default_status ;
	 }
	  $sql = "update #__dtregister_user set cancel=".$cancel."  where userId=".$userId;

		 $database->setQuery($sql);

			$database->query();
	 $sql ="insert into #__dtregister_group_amount

	(groupId,numberOfPerson,amount)values('$gid','$memtot','$amount')";

	 $database->setQuery($sql);

	 $database->query();
    
     if(isset($_POST['sendemail'])){
	    registration_email_frontend($userId);
	}
	
	 //Redirect user
 
	$mainframe->redirect('index2.php?option=com_dtregister&task=listregistrations&event_id='.$eventId);

}

function registration_email($userId){

	global $database,$mosConfig_live_site,$mosConfig_absolute_path,$DT_mailfrom,$DT_fromname,$Itemid,$my;

	$database = &JFactory::getDBO();

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

	$conf = &JFactory::getConfig();

 // $mosConfig_mailfrom = $conf->_registry['config']['data']->mailfrom;

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

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

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

	'Credit Card (Authorize.net)'=>JText::_('AUTH_NET'),'E-Check (Authorize.net)'=>JText::_('ECHECK'));

	//Currency symbol

	$arrCode=array();

	$arrSymbol=array();

	$arrCode[]='USD';$arrSymbol[]='$';

  $arrCode[]='BRL';$arrSymbol[]='R$';

  $arrCode[]='ZAR';$arrSymbol[]='R';

	$arrCode[]='GBP';$arrSymbol[]='&#163;';

	$arrCode[]='EUR';$arrSymbol[]='&#128;';

	$arrCode[]='JPY';$arrSymbol[]='&#165;';

	$arrCode[]='CHF';$arrSymbol[]='&#8355;';

	$index=-1;

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

	{

		if($arrCode[$i]==$currency_code)

		{

			$index=$i;

			break;

		}

	}

	if($index!=-1){

		$currency_symbol=$arrSymbol[$index];

	} else {

		$currency_symbol='$';

	}

	$sql="Select * From #__dtregister_user u inner join #__dtregister_group dg on dg.useid= u.userId inner join #__dtregister_group_amount ga on ga.groupId = dg.groupId  where u.userId=$userId";

	$database->setQuery($sql);

	$rowUser = $database->loadObject();

	 $address= stripslashes($rowUser->userAddress);
	 
	  $address2= stripslashes($rowUser->userAddress2);

	 $city = stripslashes($rowUser->userCity);

	 $zip = stripslashes($rowUser->userZip);

	 $state = stripslashes($rowUser->userState);

	 $email = stripslashes($rowUser->userEmail);

	 $country = stripslashes($rowUser->userCountry);

	 $fname = stripslashes($rowUser->userFirstName);

	 $lname = stripslashes($rowUser->userLastName);

     $title= (stripslashes($rowUser->userTitle)=="")?'':stripslashes($rowUser->userTitle)." "; 
	 
	 $phone = stripslashes($rowUser->userPhone);

	 $org = stripslashes($rowUser->userOrganization);

	$type = $rowUser->payment_type;

	 $eventId = $rowUser->eventId;

	 $amount  = $rowUser->amount;

	 $memtot  = $rowUser->numberOfPerson;

	 $userType = $rowUser->userType;

	// for the custom email
     $address2_display = "";
   $comma = "";
   if($address2!=""){
      $address2_display = $address2."<br />";
	  $comma = ",";
	  
   }
	$contactDetails = $address.'<br />'.$address2_display.$city.', '.$state.' '.$zip.'<br />'.$phone.'<br />'.$email;

	$msg = '';

	$msg .= '<table><link href="components/com_dtregister/assets/css/main.css" rel="stylesheet" type="text/css">';

	$msg .= '<h3>'.JText::_( 'DT_REGISTRATION_DETAILS').':</h3>';

	$msg .= '<table class="message">';

	$msg .= "<tr><td colspan=2>$thanksmsg</td></tr>";

	$msg .= '<tr><td>'.JText::_( 'DT_NAME').': </td><td>'.$title.$fname.' '.$lname.'</td></tr>';

	$msg .= '<tr><td rowspan="2">'.JText::_( 'DT_ADDRESS').': </td><td>'.$address.'</td></tr>';
	
	 if($address2 != ""){
	  $msg .= '<tr><td rowspan="2">'.JText::_( 'DT_ADDRESS2').': </td><td>'.$address2.'</td></tr>';
	}

	$msg .= '<tr><td>'.$city.' '.$state.' '.$zip.'</td><tr>';

	$msg .= '<tr><td>'.JText::_( 'DT_AMOUNT').': </td><td>'.$currency_symbol. numberFormat($amount,2).'</td></tr><tr><td><h3>'.JText::_( 'DT_THANKS_PAYPAL').'</h3></td></tr>';

	  $msg.'<tr><td><a href="'.$mosConfig_live_site.'">'.JText::_( 'RETURN_TO_SITE').'</a></td></tr></table>';

	//Get custom fields and store in CustomFields array

	$sql="Select fe.name , fe.label From #__dtregister_field_event fe inner join #__dtregister_fields df on fe.field_id=df.id where fe.event_id=$eventId and (fe.showed=1 or (fe.showed =2 and df.showed=1)) order by df.ordering ";

	$database->setQuery($sql);

	$rows1=$database->loadObjectList();

	$arrCustomFields=array();

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

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

		array_push_associative($arrCustomFields,$tmparray);

	}

	// send out emails to the registant and the admin

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

	$database->setQuery($sql);

	$eventName=$database->loadResult();

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

	$database->setQuery($sql);

	$eventBegin=$database->loadResult();

		// $subthanksemail = sprintf($subthanksemail,$eventName);

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

		$amountCharged = $amount ;

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

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

		$adminmsg="";

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

	$database->setQuery($sql);

		$row = $database->loadObject();

			$adminmsg.= $title.$fname . ' ' . $lname . ' ' . JText::_('DT_ADMIN_MESSAGE') . ' ' . $eventName . ' (' . get_date($eventBegin,$row->dtend,null,true) . ').<br><br>';

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

		$eventName=$row->summary;

		$startDate=$row->dtstart;

		$endDate=$row->dtend;

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

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

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

		if($start_date != $end_date ){

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

		}

		$adminmsg.="<table>";

		$adminmsg.="<tr><td>Event Name: </td><td>".$eventName."</td></tr>";

		$adminmsg.="<tr><td>Event Date: </td><td>".$event_date."</td></tr>";

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

		if($org != NULL){$adminmsg.="<tr><td>".JText::_('DT_ORGANIZATION').": </td><td> $org</td></tr>";}
        
        $address2_display = "";
	   $comma = "";
	   if($address2!=""){
		  $address2_display = $address2."<br />";
		  $comma = ",";
		  
	   }
		if(($address.$address2) != NULL){$adminmsg.="<tr><td>".JText::_('DT_ADDRESS').": </td><td> $address $comma $address2</td></tr>";}

		if($city != NULL){

			if($state != NULL){

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

			} else {

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

			}

		}

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

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

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

		$contactCustomFields = '';

		if ($arrCustomFields){

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

				if($rowUser->$key==""){

					continue;

				}

				$adminmsg .= "<tr><td>".$value.':</td><td>'.$rowUser->$key.'</td></tr>';

				$contactCustomFields .= $value.': '.$rowUser->$key.'<br />';

			}

		}

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

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

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

        if($rowUser->discount_code_id != 0 && $rowUser->discount_code_id !=''){

			$dt_code = new DiscountCode($rowUser->discount_code_id);

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

	    }

		if ($userType == 'G'){

			$adminmsg.="<tr><td colspan=2>".JText::_('DT_ADMIN_GROUP_DETAILS').": </td></tr>";

			// get the details of the group users

			$sql2 = "SELECT m.* FROM #__dtregister_group_member m, #__dtregister_group g

					WHERE g.useid={$userId} AND g.groupId=m.groupUserId";

			//$adminmsg.=$sql2;

			$database->setQuery($sql2);

			$rowUser2=$database->loadObjectList();

			//$memtot = count($rowUser);

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

			$groupCustomFields = '';
            $memberNames = "";
			for ($i=0,$n=count($rowUser2);$i<$n;$i++){

				$row=$rowUser2[$i];

				$adminmsg.="<tr><td colspan=2><br><br>".JText::_('DT_MEMBER') .($i+1)."</td></tr>";
 
				if ($row->lastname){
                 if($row->title !=""){
				    $mtitle = $row->title." ";
				 }
				$adminmsg.="<tr><td>".JText::_('DT_NAME').": </td><td>".$mtitle.$row->firstname . ' ' .$row->lastname."</td></tr>";

				$memberNames .= ' ' . stripslashes($mtitle.$row->firstname);

				$memberNames .= ' ' . stripslashes($row->lastname)."<br>";

				}

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

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

				if ($row->city || $row->state || $row->country){

					$adminmsg.="<tr><td>";

						if ($row->city){$adminmsg.=JText::_('DT_CITY');}

						if ($row->state || $row->country){$adminmsg.=' ('.JText::_('DT_STATE');}

						if ($row->state && $row->country){$adminmsg.=', ';}

						if ($row->country){$adminmsg.=JText::_('DT_COUNTRY');}

						if ($row->state || $row->country){$adminmsg.=')';}

						$adminmsg.=": </td><td>";

						if ($row->city){$adminmsg.=$row->city;}

						if ($row->state || $row->country){$adminmsg.=' ('.$row->state;}

						if ($row->state && $row->country){$adminmsg.=', ';}

						if ($row->country){$adminmsg.=$row->country;}

						if ($row->state || $row->country){$adminmsg.=')';}

						$adminmsg.="</td></tr>";

				}

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

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

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

				if ($arrCustomFields){

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

						if($row->$key ==""){

							continue;

						}

						if ($row->$key){

							$adminmsg .= "<tr><td>".$value.':</td><td>'.$row->$key.'</td></tr>';

							 $groupCustomFields .= $value.': '.$row->$key.'<br />';

						}

					}

				}

			}

		}

		$adminmsg.="</table></pre>";

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

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

	$database->setQuery($sql);

	$rowAdminEmail = $database->loadObject();

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

    $database->setQuery($sql1);

	$defaultthksmsg = $database->loadResult();

    if($rowAdminEmail->email){

		$adminemail=$rowAdminEmail->email;

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

		$thksmsg_set=$rowAdminEmail->thksmsg_set;

		$eventBegin=$rowAdminEmail->publish_up;

		$eventEnd=$rowAdminEmail->publish_down;

		$eventTitle=$rowAdminEmail->title;

	} else {

		$adminemail=$DT_mailfrom;

	}

	// If custom email message is selected... use it!
    $evt =  new Event($eventId);
		
		$location = $evt->get_location();

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

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

		$replace = array($fname,$title.$fname.' '.$lname, $org, $eventName, JHTML::_('date', $eventBegin), $contactDetails, isset($memberNames)?$memberNames:'', $memtot, numberFormat($amount,2), $lang_var[$type], $contactCustomFields, isset($groupCustomFields)?$groupCustomFields:'',$rowUser->confirmNum,$location===false?'':$location->name);

    if ($thksmsg_set == 1){

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

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

		$subthanksemail = str_replace('[EVENT_DATE]',JHTML::_('date', $eventBegin),$subthanksemail);

	} else {

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

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

		$subthanksemail = str_replace('[EVENT_DATE]',JHTML::_('date', $eventBegin),$subthanksemail);

	}

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

    $database->setQuery($sql);

	  $subthanksemail = $database->loadResult();

     $user_thanksemail	= stripslashes($thanksemail);

    $subthanksemail = str_replace('[EVENT_DATE]',get_date($eventBegin,$eventEnd),$subthanksemail);

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

		$adminmsg 		= stripslashes($adminmsg);

		$subadmin 		= stripslashes($subadmin);

		$subthanksemail = stripslashes($subthanksemail);

		# send them out

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

		if ($pos === false) { 

			$adminemails = array($adminemail);

		}else{

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

		}

		foreach($adminemails as $value){

			JUTility::sendMail($DT_mailfrom, $DT_fromname,$value,$subadmin,nl2br($adminmsg),1);

		}

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

		// send out the users email

	$evt =  new Event($eventId);

    $data = $evt->get_files();

	$attachments  = null ;

	foreach($data as $file){

		$attachments[] = $file->path;

	}

	$mail =& JFactory::getMailer();
    //$dt_user = new DT_User($userId,$eventId);
   ///$user_thanksemail =  parse_tags_new(($user_thanksemail),$dt_user); 
	JUTility::sendMail( $DT_mailfrom, $DT_fromname,$email,$subthanksemail,($user_thanksemail),1,null,null,$attachments);

}

function cancelNewMember($option)

{

	global $mainframe;

	$mainframe->redirect('index2.php?option=com_dtregister&task=listregistrations');

}

function groupRegistrationForm($option)

{

	global $mosConfig_dbprefix;

	$database = &JFactory::getDBO();

	$mosConfig_live_site = JURI::base( true );

	//Require the config file

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

	//End of the config file

	$eventId=JRequest::getInt('event_id',0);
    $dt_event = new Event($eventId);
	$userId=JRequest::getInt('user_id',0);

	$sql="Select id, CONCAT(name, ' (', username  ,')') fullname From #__users order by name";

	$database->setQuery($sql);

	$rowUsers=$database->loadObjectList();

	$options=array();

	$options[] = JHTML::_('select.option', "0","Select user","id","fullname");

	$rowUsers=array_merge($options,$rowUsers);

	$javascript=" onchange=document.adminForm.submit(); ";

	$lists["user_list"]=JHTML::_('select.genericlist', $rowUsers,"user_id",$javascript,"id","fullname",$userId);

	if($userId && $cb_integrated)

	{

		//Get the user detail

		$sql="Select a.id,a.email,b.*

			From #__users As a

			Inner Join #__comprofiler As b

			On a.id=b.user_id

			Where a.id=$userId

			";

		$database->setQuery($sql);

		$rowProfile = $database->loadObject();

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

			if(substr($key,0,3)=="cb_"){

				$chg_key = str_replace('cb_','',$key);

				$rowProfile->{$chg_key} = $value;

			}

		}

	}

	else

	{

		$rowProfile=null;

	}

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

	$database->setQuery($sql);

	$rows=$database->loadObjectList();
    $fld = new Custom_field();
    $fields=array() ;
	$fld->getAllFields($eventId,'M',true,0,$fields) ;
	$rows = $fields ; 	
	$arrFieldIds=array();
   
	for($i=0,$n=count($rows);$i<$n;$i++)

	{

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

	}

	if(count($arrFieldIds))

	{

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

		$database->setQuery($sql);

		if($database->getErrorMsg())

			echo $database->getErrorMsg();

		$rowCustoms=$database->loadObjectList();

	}

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

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

	$database->setQuery($sql);

	$eventdata=$database->loadObject();

 	$eventName= $eventdata->summary ;

	$eventBegin = $eventdata->dtstart ;

    $eventEnd=$eventdata->dtend ;

	$latefee=JRequest::getVar('latefee');

	$submited=JRequest::getInt('submited',0);

	$memTot=JRequest::getInt('memtot',0);

	if($submited)

		$amountCharged=JRequest::getVar('org_amountCharged');

	else

		 $amountCharged=JRequest::getVar('amountCharged');

	$orgAmountCharged=$amountCharged;

	 $amountCharged=$amountCharged + $latefee;

	/* $dt_reg = new DT_User(null,$eventId);

	 $dt_reg->calculate_fee($memTot,$_POST['user_id']);

	 $dt_reg->event->member_discount;*/

	//Get data passed by hidden variables
    
	if($m_s_title)

	{

		$arrTitle=JRequest::getVar('arr_title',array(),'post','array');

	}

	if($m_s_firstname)

	{

		$arrFirstName=JRequest::getVar('arr_firstname',array(),'post','array');

	}

	if($m_s_lastname)

	{

		$arrLastName=JRequest::getVar('arr_lastname',array());

	}

	if($m_s_organization)

	{

		$arrOrganization=JRequest::getVar('arr_organization',array());

	}

	if($m_s_address)

	{

		$arrAddress=JRequest::getVar('arr_address',array());

	}
	
	if($m_s_address2)

	{

		$arrAddress2=JRequest::getVar('arr_address2',array());

	}

	if($m_s_city)

	{

		$arrCity=JRequest::getVar('arr_city',array());

	}

	if($m_s_state)

	{

		$arrState=JRequest::getVar('arr_state',array());

	}

	if($m_s_zip)

	{

		$arrZip=JRequest::getVar('arr_zip',array());

	}

	if($m_s_country)

	{

		$arrCountry=JRequest::getVar('arr_country',array());

	}

	if($m_s_email)

	{

		$arrEmail=JRequest::getVar('arr_email',array());

	}

	if($m_s_phone)

	{

		$arrPhone=JRequest::getVar('arr_phone',array());

	}

	if(isset($rowCustoms))

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

	{

		$rowCustom=$rowCustoms[$i];

		$name=$rowCustom->name;

		$arrName="arr_$name";

		if(isset($_POST[$arrName]))

		{

			$arrName="arr_$name";

			$$arrName=JRequest::getVar($arrName,array());

		}else{
			
			$$arrName = "" ;
		}

	}

	//Get data passed from the last form

	if(!$submited)

	{
        
		if($m_s_title)

		{

			$title=JRequest::getVar('title','');

			$arrTitle[]=$title;

		}
		
		if($m_s_firstname)

		{

			$firstName=JRequest::getVar('firstname','');

			$arrFirstName[]=$firstName;

		}

		if($m_s_lastname)

		{

			$lastName=JRequest::getVar('lastname','');

			$arrLastName[]=$lastName;

		}

		if($m_s_organization)

		{

			$organization=JRequest::getVar('organization','');

			$arrOrganization[]=$organization;

		}

		if($m_s_address)

		{

			$address=JRequest::getVar('address','');

			$arrAddress[]=$address;

		}
		
		if($m_s_address2)

		{

			$address2=JRequest::getVar('address2','');

			$arrAddress2[]=$address2;

		}

		if($m_s_city)

		{

			$city=JRequest::getVar('city','');

			$arrCity[]=$city;

		}

		if($m_s_state)

		{

			$state=JRequest::getVar('state','');

			$arrState[]=$state;

		}

		if($m_s_zip)

		{

			$zip=JRequest::getVar('zip','');

			$arrZip[]=$zip;

		}

		if($m_s_country)

		{
            
			$country=JRequest::getVar('country','');

			$arrCountry[]=$country;

		}

		if($m_s_email)

		{

			$arrEmail[]=JRequest::getVar('email','');

		}

		if($m_s_phone)

		{

			$phone=JRequest::getVar('phone','');

			$arrPhone[]=$phone;

		}

		if(isset($rowCustoms))

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

		{

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$type=$rowCustom->type;

			if(isset($_POST[$name]))

			{

				$value= JRequest::getVar($name,array());

				if($type==3)

				{

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

				}

				$arrName="arr_$name";
                if(!isset($$arrName)){
				   $$arrName =  "";
				}
				array_push($$arrName,$value);

			}else{
				$arrName="arr_$name";
				array_push($$arrName,"");
			}

		}

	}

	if(isset($rowCustoms))

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

	{

		$rowCustom=$rowCustoms[$i];

		$name=$rowCustom->name;

		//echo "</pre>";

		$arr_name = "arr_".$name;

		if(!isset($_POST[$arr_name]))

		{

			continue;

		}

		if(!$rowCustom->fee_field)

		{

			continue;

		}

		$customType=$rowCustom->type;

		$values=$rowCustom->values;

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

		$fees=$rowCustom->fees;

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

		//Loop over every members and modify the code

		$arrName="arr_$name";

		$arrMemberData=$$arrName;

		for($k=0;$k<count($arrMemberData);$k++)

		{

			$postedValue=$arrMemberData[$k];
            if($postedValue != "")
			for($j=0,$m=count($arrValues);$j<$m;$j++)

			{

				if($customType==3)

				{

					if(strpos('|',$postedValue)!==false){

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

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

						{

							$amountCharged+=$arrFees[$j];

						}

					}else{

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

						{

							$amountCharged+=$arrFees[$j];

						}

					}

				}

				else

				{

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

					{

						$amountCharged+=$arrFees[$j];

						break;

					}

				}

			}

		}

	}

  ?>

  <script type="text/javascript">

  function submitbutton(pressbutton){

  if(pressbutton=="cancel_registration")

  {

  	submitform(pressbutton);

  	return;

  }

  var frm= document.adminForm;

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

  alert('Please enter first name');

  frm.fname.focus();

  return;

  }

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

  alert('Please enter last name');

  frm.lname.focus();

  return;

  }

if(frm.payment_type.value==''){

  alert('Please Select Payment Type');

  frm.payment_type.focus();

  return;

  }

  <?php

		if(isset($p_organization) && $p_organization)

		{

		?>

			if(frm.org.value=="")

			{

				alert ("Please enter organization");

				frm.org.focus();

				return  ;

			}

		<?php

		}

	?>

  /*

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

  alert('Please enter Organization name');

  frm.org.focus();

  return;

  }

  */

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

  alert('Please enter address');

  frm.address.focus();

  return;

  }

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

  alert('Please enter city');

  frm.city.focus();

  return;

  }

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

  alert('Please enter zip code');

  frm.zip.focus();

  return;

  }

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

  alert('Please enter state');

  frm.state.focus();

  return;

  }

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

  alert('Please enter email');

  frm.email.focus();

  return;

  }

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

  alert('Please enter email confirmation');

  frm.cemail.focus();

  return;

  }

  if(frm.email.value!=frm.cemail.value){

  alert('Confirmation Email does not match the email address entered');

  frm.cemail.focus();

  return;

  }

  var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

  var returnval=emailfilter.test(frm.email.value)

	if (returnval==false){

	alert("Please enter a valid email address.");

    frm.email.select();

	frm.email.focus();

	return ;

	}

	<?php

		if(isset($p_phone) && $p_phone)

		{

		?>

			if(frm.phone.value=="")

			{

				alert ("Please enter phone number");

				frm.phone.focus();

				return  ;

			}

		<?php

		}

	?>

	submitform(pressbutton);

  }

  function chknumber(txtname)

{

	var num = txtname.value

	if(isNaN(num))

	{

		alert("You can enter only the number")

		txtname.value = "";

		txtname.focus();

	}

}

  </script>

  <link rel="stylesheet" href="<?php echo $mosConfig_live_site;?>/components/com_dtregister/assets/css/main.css" type="text/css">

<?php

$sql="Select use_discountcode from #__dtregister_group_event where eventId=$eventId limit 0,1";

$database->setQuery($sql);

$use_discountcode=$database->loadResult();

?>

  <form name="adminForm" id="adminForm" method="post" action="index2.php">

  <div class="componentheading"><?php echo JText::_( 'DT_REGISTRATION' );?>: <?php echo $eventName?> (<?php echo get_date($eventBegin,$eventEnd,null,true);?>)</div>

  <table class="authorizenetformtable" cellspacing="2" cellpadding="2" border="0">

  <tr><td><?php echo $topmsg; ?></td></tr>

<?php

      $arrCode=array();

		$arrSymbol=array();

		$arrCode[]='GBP';$arrSymbol[]='&#163;';

		$arrCode[]='EUR';$arrSymbol[]='&#128;';

		$arrCode[]='JPY';$arrSymbol[]='&#165;';

		$arrCode[]='CHF';$arrSymbol[]='&#8355;';

		$index=-1;

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

			if($arrCode[$i]==$currency_code){

				$index=$i;

				break;

			}

		}

		if($index!=-1){

			$currency_symbol=$arrSymbol[$index];

		} else {

			$currency_symbol='$';

		}

?>

  <tr><td class="contentheading"><?php echo JText::_( 'TOTAL_REGISTRATION_COST' );?>: <?php echo $currency_symbol?><?php echo numberFormat($amountCharged,2)?>

  </td></tr>

  </table>

  <link rel="stylesheet" href="<?php echo $mosConfig_live_site;?>/components/com_dtregister/assets/css/main.css" type="text/css">

  <table align='center' width='100%' border='0' cellpadding='2' cellspacing='2' class="adminform">
<tbody>
  <tr><td colspan="3" align="left" ><strong><?php echo JText::_( 'DT_BILLING_INFORMATION' );?></strong></td></tr>

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

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

	  <td>

	  		<?php

	  			echo $lists["user_list"];

	  		?>

	  </td>
 <td width="2%" >&nbsp;</td>
  </tr>

<?php if($use_discountcode){ ?>

<tr><td><?php echo JText::_( 'DT_DISCOUNT_CODE' ); ?>:</td><td><input type="text" name="discount_code" value="" class="inputbox" /></td> <td width="2%" >&nbsp;</td></tr>

<?php } ?>

   <tr><td><?php echo JText::_( 'DT_TITLE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td>
   <?php
      $titles = explode("|",$titleoptions);
	  $temp[] = JHTML::_('select.option', '', JText::_( 'DT_SELECT_ONE'));

	  foreach($titles as $title){
	
		$temp[] = JHTML::_('select.option', $title, $title);
	
	 }
	        
	 $titles = $temp;
	 echo  JHTML::_('select.genericlist',$temp,"title", 'class="inputbox" size="1"', 'value', 'text');
   ?>
   
   </td> <td width="2%" >&nbsp;</td></tr>
   
  <tr><td><?php echo JText::_( 'DT_FIRSTNAME' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="fname" value="<?php echo isset($rowProfile->firstname)?$rowProfile->firstname:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_LASTNAME' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="lname" value="<?php echo isset($rowProfile->lastname)?$rowProfile->lastname:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_ORGANIZATION' );?>:

  <?php

  	if(isset($p_organization) && $p_organization)

	{

	?>

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

	<?php

	}

  ?>

  </td><td><input type="text" class="inputbox" name="org" value="<?php echo isset($rowProfile->company)?$rowProfile->company:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_ADDRESS' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="address" size="40" value="<?php echo isset($rowProfile->address)?$rowProfile->address:''?>"> </td> <td width="2%" >&nbsp;</td></tr>
  
  <tr><td><?php echo JText::_( 'DT_ADDRESS2' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="address2" size="40" value="<?php echo isset($rowProfile->address2)?$rowProfile->address2:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_CITY' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="city" value="<?php echo isset($rowProfile->city)?$rowProfile->city:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_STATE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="state" value="<?php echo isset($rowProfile->state)?$rowProfile->state:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_ZIPCODE' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="zip" value="<?php echo isset($rowProfile->zipcode)?$rowProfile->zipcode:''?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <?php require_once(JPATH_SITE.'/components/com_dtregister/country.htm');?>

  <tr><td><?php echo JText::_( 'DT_PHONE' );?>:&nbsp;

  <?php

      	if(isset($p_phone) && $p_phone)

		{

		?>

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

		<?php

		}

   ?>

  </td><td><input type="text" class="inputbox" name="phone" value="<?php echo isset($rowProfile->phone)?$rowProfile->phone:''?>">

  </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_EMAIL' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="email" size="30" value="<?php echo isset($rowProfile->email)?$rowProfile->email:'';?>"> </td> <td width="2%" >&nbsp;</td></tr>

  <tr><td><?php echo JText::_( 'DT_CONFIRM_EMAIL' );?>:<span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></td><td><input type="text" class="inputbox" name="cemail" size="30" value="<?php echo isset($rowProfile->email)?$rowProfile->email:'';?>"> </td> <td width="2%" >&nbsp;</td></tr>
  
  <tr>
    <td><?php echo JText::_( 'DT_AMOUNT_PAID' );?>:</td><td><input type="text" class="inputbox" name="paid_amount" size="30" value=""></td>
     <td width="2%" >&nbsp;</td>
  </tr>

  <?php

  	//Will display payment method selection here

  	$options=array();

	$options=array();

	$options[]=JHTML::_('select.option', '','Select payment method');

	$options[]=JHTML::_('select.option', 'Authorize.net',JText::_('AUTH_NET'));
    $options[]=JHTML::_('select.option', 'Echeck',JText::_('ECHECK'));
	$options[]=JHTML::_('select.option', 'GoogleCheckout', JText::_( 'DT_GOOGLE_CHECKOUT' ));
	
	$options[]=JHTML::_('select.option', 'PayPal',JText::_('PAYPAL'));
    $options[]=JHTML::_('select.option', 'Eway', JText::_( 'DT_EWAY' ));
	$options[]=JHTML::_('select.option', 'ideal',JText::_('DT_PAY_IDEAL'));
    $options[]=JHTML::_('select.option', 'idealRabo', JText::_( 'DT_PAY_IDEAL_LITE' ));
	$options[]=JHTML::_('select.option', 'NetDeposit', JText::_( 'DT_NETDEPOSIT' ));
	$options[]=JHTML::_('select.option', 'Mail',JText::_('DT_MAILIN_PAYMENT'));

	$options[]=JHTML::_('select.option', 'Phone',JText::_('DT_CALLIN_PAYMENT'));

	$options[]=JHTML::_('select.option', 'At_door',JText::_('DT_PAY_AT_DOOR'));
    
	$lists["payment_type"]=JHTML::_('select.genericlist', $options,'payment_type','','value','text','');

  ?>

  <tr>

  	<td>

  		<?php

  			echo JText::_( 'DT_PAYMENT_METHOD' );

  		?>

  	</td>

  	<td>

  		<?php

  			echo $lists["payment_type"];

  		?>

  	</td>
 <td width="2%" >&nbsp;</td>
  </tr>

  <tr>

  	<td>

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

  	</td>

  	<td>

  		<?php

  			echo JHTMLSelect::booleanlist("pay_later_paid","",1);

  		?>

  	</td>
 <td width="2%" >&nbsp;</td>
  </tr>
 <tr><td><?php echo JText::_( 'DT_SEND_EMAIL' );?>:</td><td><input type="checkbox" checked class="inputbox" name="sendemail" size="30" value=""> </td>
  <td width="2%" >&nbsp;</td>
 </tr>
<?php

  ##################custom fields
   echo $dt_event->field_html('B',null,true,'adminForm');
	$sql="Select * From #__dtregister_fields df inner join #__dtregister_field_event fe on fe.field_id = df.id

		where fe.event_id=$eventId and ((fe.showed in(2,3)) or (fe.showed =-1 and df.showed in(2,3))) and df.published=1 order by ordering ";

		$database->setQuery($sql);

		//echo $database->getQuery();

		if($database->getErrorMsg())

			echo $database->getErrorMsg();

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

?>
</tbody>
</table>

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

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

<!-- Other hidden variables-->

<input type="hidden" name="memtot" value="<?php echo $memTot?>">

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

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

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

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

<input type="hidden" name="submited" value="1" />

<!--Pass member's data as hidden variables -->

<?php
   if($m_s_title)

		{

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

			{

				$value=$arrTitle[$i];

			?>

				<input type="hidden" name="arr_title[]" value="<?php echo $value;?>" />

			<?php

			}

		}
if($m_s_firstname)

		{

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

			{

				$value=$arrFirstName[$i];

			?>

				<input type="hidden" name="arr_firstname[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_lastname)

		{

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

			{

				$value=$arrLastName[$i];

			?>

				<input type="hidden" name="arr_lastname[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_organization)

		{

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

			{

				$value=$arrOrganization[$i];

			?>

				<input type="hidden" name="arr_organization[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_address)

		{

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

			{

				$value=$arrAddress[$i];

			?>

				<input type="hidden" name="arr_address[]" value="<?php echo $value;?>" />

			<?php

			}

		}
		
		if($m_s_address2)

		{

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

			{

				$value=$arrAddress2[$i];

			?>

				<input type="hidden" name="arr_address2[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_city)

		{

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

			{

				$value=$arrCity[$i];

			?>

				<input type="hidden" name="arr_city[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_state)

		{

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

			{

				$value=$arrState[$i];

			?>

				<input type="hidden" name="arr_state[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_zip)

		{

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

			{

				$value=$arrZip[$i];

			?>

				<input type="hidden" name="arr_zip[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_country)

		{

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

			{

				$value=$arrCountry[$i];

			?>

				<input type="hidden" name="arr_country[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_email)

		{

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

			{

				$value=$arrEmail[$i];

			?>

				<input type="hidden" name="arr_email[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		if($m_s_phone)

		{

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

			{

				$value=$arrPhone[$i];

			?>

				<input type="hidden" name="arr_phone[]" value="<?php echo $value;?>" />

			<?php

			}

		}

		//Hidden variables for custom fields

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

		{

			$rowCustom=$rowCustoms[$i];

			$name=$rowCustom->name;

			$arrName="arr_".$name;
			

			//if(1)
            if(isset($_POST[$arrName]) || isset($_POST[$name]))
			{

				$arrName="arr_".$name;
               $arrValues=$$arrName;
				

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

				{

					$value=$arrValues[$j];

				?>

					<input type="hidden" name="<?php echo $arrName; ?>[]" value="<?php echo $value ?>" />

				<?php

				}

			}else{
			   ?>

					<input type="hidden" name="<?php echo $arrName; ?>[]" value="" />

				<?php
			}

		}

?>

<!-- End pass data as hidden variables-->

 </form>

 <script src="<?php echo Juri::root();  ?>/components/com_dtregister/assets/js/jquery.js" type="text/javascript"></script>
  <script type="text/javascript">
  
DTjQuery(function(){
  DTjQuery('.upload').live('click',function(){
	   
	   DTjQuery(this.form).attr('target','fileupload');
	   prevtask = DTjQuery(this.form.task).val();
	   prevtype = DTjQuery(this.form.type).val();
	   var filesizes = DTjQuery(this).attr('filesize');
	   var filetype = DTjQuery(this).attr('filetype');
	   var name = DTjQuery(this).attr('filename');
	  
	   DTjQuery(this.form.type).val(name+'|'+filesizes+'|'+filetype);
	   
	   DTjQuery(this.form.task).val('fileupload');
	   DTjQuery(this.form.option).val('com_dtregister');
	   DTjQuery(this.form.option).val('com_dtregister');
	   
	   DTjQuery(this.form).submit();
	   
	   DTjQuery(this.form.task).val(prevtask);
	   DTjQuery(this.form.type).val(prevtype);
	   DTjQuery(this.form).attr('target','');
	   return false;
	});
})
</script>
<?php

}

function insertTable($arrFields,$arrValues,$tableName)

{

	$database = &JFactory::getDBO();

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

	{

		$arrFields[$i]=$database->NameQuote($arrFields[$i]);

		$arrValues[$i]=$database->Quote($arrValues[$i]);

	}

	$sql="Insert into $tableName(".implode(",",$arrFields).") Values (".implode(",",$arrValues).")";

	$database->setQuery($sql);

	$database->query();

	if($database->getErrorMsg())

	{

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

		return 0;

	}

	else

	{

		return $database->insertid();

	}

}

function mycategories($option){

	global $mainframe;

	$database = &JFactory::getDBO();

	$sql="Select * From #__dtregister_categories order by ordering";

	$database->setQuery($sql);

	$rows=$database->loadObjectList();

	include_once( "includes/pageNavigation.php" );

	$pageNav = new mosPageNav( count($rows), $limitstart=1, $limit=10  );

	HTML_groups::showcategories($option,$rows,$pageNav);

}

function editcategory( $option) {

    global $mainframe;

	$database = &JFactory::getDBO();

    $id=$_GET['id'];

    $sql='Select * From #__dtregister_categories WHERE categoryId=' . $database->Quote( $id );

	  $database->setQuery($sql);

  	$rows=$database->loadObjectList();

    HTML_groups::editingcategory($option,$rows);

}

function savecategory($option) {

	global $mainframe;

   	$database = &JFactory::getDBO();

    $catid=JRequest::getVar('catid');

    $catname=JRequest::getVar('catname');
	
	$parent_id=JRequest::getVar('parent_id');

    $sql='UPDATE  #__dtregister_categories SET categoryName=' . $database->Quote( $catname ) . ' , parent_id='.$parent_id.' WHERE categoryId=' . $database->Quote( $catid );

  	$database->setQuery($sql);

    if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

		exit();

	}

	 $mainframe->redirect("index2.php?option=com_dtregister&act=categories");

}

function newcategory($option) {

   $database = &JFactory::getDBO();

   $query = "Select * from #__dtregister_categories where parent_id=0";
   
   $database->setQuery($query);
   $rows=$database->loadObjectList();
   $options = array();
   $options[] = JHTML::_('select.option',0,JText::_( 'DT_SELECT_PARENT' ));
   foreach($rows as $cat){
      
	  $options[] = JHTML::_('select.option',$cat->categoryId,$cat->categoryName);
	  
   }
   $list['parent_id'] = JHTML::_('select.genericlist', $options,"parent_id","","value","text");
   HTML_groups::new_category($option,$list);

}

function savenewcategory($option) {

	global $mainframe;

	$database = &JFactory::getDBO();

    $catname=$_POST['catname'];
	
	 $parent_id=$_POST['parent_id'];

    $sql="INSERT INTO #__dtregister_categories(`categoryName`,`parent_id`) VALUES ('$catname',$parent_id)";

	$database->setQuery($sql);

    if (!$database->query()) {

		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

		exit();

	}

	$categoryId= $database->insertid();

	$sql = "select count(*) as count_cat from #__dtregister_categories";

	$database->setQuery($sql);

	$rows=$database->loadResult();

	$sql = "Update #__dtregister_categories set ordering = '".$rows."' where categoryId = '".$categoryId."'";

	$database->setQuery($sql);

	$database->query();

	 $mainframe->redirect("index2.php?option=com_dtregister&act=categories");

}

function cancelnewcategory($option)

{

	global $mainframe;

 $mainframe->redirect('index2.php?option=com_dtregister&act=categories');

}

function deletecategories(){
    
	global $mainframe;
    $categories  = JRequest::getVar( 'cid', array(0), 'request', 'array' );
	$database = &JFactory::getDBO();
	$warning = false ;
	$message =  false ;
	foreach($categories as $category){
		$sql='Select slabId From #__dtregister_group_event WHERE category=' . $database->Quote( $category );
	
		$database->setQuery($sql);
	
		$total=$database->loadResult();
	
		if ($total){
		    
			$warning =  true ;
		   
		}else{
		   $message =  true ;
		   $sql1='DELETE FROM  #__dtregister_categories WHERE categoryId=' . $database->Quote( $category );

		   $database->setQuery($sql1);
		
		   $database->query();
		  
		}
	}
	
	$msg = "";
	
	if($warning){
	    
		$msg = JText::_( 'DT_CATEGORY_DELETE_WARNING' );
		
	}
	if($message){
	   
	   $msg .=  " ".JText::_( 'DT_CATEGORY_DELETED' );
	   
	}
	 
	$mainframe->redirect( "index2.php?option=com_dtregister&act=categories",$msg );
	
}

function deletecategory($option,$id) {

    global $mainframe;

	$database = &JFactory::getDBO();

    $id=JRequest::getVar('id');

    $sql='Select slabId From #__dtregister_group_event WHERE category=' . $database->Quote( $id );

	$database->setQuery($sql);

	$total=$database->loadResult();

    if ($total){

    $value =0;

    }

    else {

    $sql1='DELETE FROM  #__dtregister_categories WHERE categoryId=' . $database->Quote( $id );

    $database->setQuery($sql1);

    $database->query();

    $value =1;

   }

    HTML_groups::deletingcategory($option,$value);

}

function reorderEvent( $uid, $inc, $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

	$sql = "SELECT eventId , category FROM  #__dtregister_group_event WHERE slabId='$uid'";

   	$database->setQuery($sql);

	$slab = $database->loadObject();

 	$row = new myGroupEventReorder( $database );

//$row =& JTable::getInstance('event');

	$row->load( (int)$slab->eventId );

	$row->reorder(' category = '.$slab->category);

	$row->move( $inc, ' category = '.$slab->category );

/*	$row->reorder(' category = '.$row->category);

  	$sql = "SELECT categoryName FROM #__dtregister_categories WHERE categoryId='$row->category'";

  	$database->setQuery($sql);

	$catRow = $database->loadResult();

	//echo "<pre>";

	//var_dump($row);

	//var_dump($catRow); die;

	###########################################################

	$dirn = $inc ;

	$where = ' category = '.$row->category;

	$wherenot = ' category <> '.$row->category;

		$k = $tbl_key = 'eventId';

		$tbl = "#__dtregister_group_event";

		$sql = "SELECT $tbl_key, ordering , category FROM $tbl";

		if ($dirn < 0)

		{

			$sql .= ' WHERE ordering < '.(int) $row->ordering;

			$sql .= ($where ? ' AND '.$where : '');

			$sql .= ' ORDER BY ordering DESC';

		}

		else if ($dirn > 0)

		{

			$sql .= ' WHERE ordering > '.(int) $row->ordering;

			$sql .= ($where ? ' AND '. $where : '');

			$sql .= ' ORDER BY ordering';

		}

		else

		{

			$sql .= ' WHERE ordering = '.(int) $row->ordering;

			$sql .= ($where ? ' AND '.$where : '');

			$sql .= ' ORDER BY ordering';

		}

		$database->setQuery( $sql );

		$row2 = null;

		$row2 = $database->loadObjectList();

		$row2 = end($row2);

		$where2 = ' category = '.$row2->category;

		if (isset($row2))

		{

			$query = 'UPDATE '. $tbl

			. ' SET ordering = '. (int) $row2->ordering

			. ' WHERE '. $tbl_key .' = '. $database->Quote($row->$k).' and '.$where ;

			;

			$database->setQuery( $query );

			if (!$database->query())

			{

				$err = $database->getErrorMsg();

				//JError::raiseError( 500, $err );

			}

			$query = 'UPDATE '. $database->Quote( $tbl )

			. ' SET ordering = '.(int) $row->ordering

			. ' WHERE '. $database->Quote( $tbl_key ) .' = '.$database->Quote($row2->$k).' and '.$where2 ;

			;

			$database->setQuery( $query );

			if (!$database->query())

			{

				$err = $database->getErrorMsg();

				//JError::raiseError( 500, $err );

			}

			$row->ordering = $row2->ordering;

		}

		else

		{

			$query = 'UPDATE '. $tbl

			. ' SET ordering = '.(int) $this->ordering

			. ' WHERE '. $tbl_key .' = '. $database->Quote($row->$k)

			;

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

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

			if (!$database->query())

			{

				$err = $database->getErrorMsg();

				JError::raiseError( 500, $err );

			}

		}*/

	############################################################

	$mainframe->redirect( "index2.php?option=com_dtregister&act=groups" );

}

function reorderCategory( $uid, $inc, $option ) {

	global $mainframe;

	$database = &JFactory::getDBO();

 	$row = new mosDtCategory( $database );

	$row->load( (int)$uid );

	$row->reorder();
   
	$row->move( $inc, "parent_id=".$row->parent_id );

	$mainframe->redirect( "index2.php?option=com_dtregister&act=categories" );

}

function saveOrderCategory($option,$cid){

	global $mainframe;

	$database = &JFactory::getDBO();

	$total		= count( $cid );

	$order	= JRequest::getVar( 'order', array(0), '', 'array' );

	$row 		= new mosDtCategory( $database );

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

		$row->load( (int) $cid[$i] );

		if ($row->ordering != $order[$i]) {

			$row->ordering = $order[$i];

			if (!$row->store()) {

				echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";

				exit();

			}

		}

	}

	$mainframe->redirect( "index2.php?option=com_dtregister&act=categories" );

}

function saveOrderEvent($option,$cid)

{

	global $mainframe;

	$database = &JFactory::getDBO();

	$total		= count( $cid );

	$order	= JRequest::getVar( 'order', array(0), '', 'array' );

	$row 		= new myGroupEventReorder( $database );

    //$row 		= new myGroupEvent( $database );

    foreach($order as $eventId=>$ordering){

	  $query = "update #__dtregister_group_event set ordering=$ordering where eventId=$eventId";

	  $database->setQuery($query);

	  $database->query();

	}
       unset($_REQUEST['task']);
	
	$_REQUEST['act'] = 'groups';
	
    $get_str = http_build_query($_REQUEST);

         $mainframe->redirect("index2.php?".$get_str);
    $mainframe->redirect("index2.php?option=com_dtregister&act=groups");

	// update ordering values

	$groupings = array();

$slab_ids = array_keys($order);

$not_in = array_diff($cid,$slab_ids);

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

	 $sql = 'SELECT slabId FROM  #__dtregister_group_event WHERE eventId=' . $database->Quote( $key ). ' and category in(select category from #__dtregister_group_event where slabId=' . $database->Quote( $value ) . ")";

		$database->setQuery( $sql );

		$row2 = null;

		$row2 = $database->loadAssocList();

		if($row2){

			foreach($row2 as $value_in){

				if(isset($order[$value_in['slabId']]) && $value_in['slabId'] != $value){

					$order[$value] = $order[$value_in['slabId']];

					break;

				}

			}

		}

}

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

				$sql = 'SELECT eventId FROM  #__dtregister_group_event WHERE slabId=' . $database->Quote( $cid[$i] );

   $database->setQuery($sql);

	$uid = $database->loadResult();

 	$cid[$i] = $uid;

		$row->load( (int) $cid[$i] );

		if ($row->ordering != $order[$row->slabId]) {

			$row->ordering = $order[$row->slabId];

			$groupings[] = $row->category;

			$row->_tbl_key = "slabId";

			if (!$row->store()) {

				echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); <//script>\n";

				exit();

			}

			$row->_tbl_key = "eventId";

		}

	}

    $groupings = array_unique( $groupings );

	  foreach ($groupings as $group){

	 		// $row->reorder('category = '.$database->Quote($group));

		}
    unset($_REQUEST['task']);
	
	$_REQUEST['act'] = 'groups';
	
    $get_str = http_build_query($_REQUEST);

         $mainframe->redirect("index2.php?".$get_str);
	$mainframe->redirect("index2.php?option=com_dtregister&act=groups");

}

function array_push_associative(&$arr) {

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

		if (is_array($arg)) {

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

				$arr[$key] = $value;

				$ret++;

			}

		}else{

			$arr[$arg] = "";

		}

	}

	return $ret;

}

function eventAttended($option,$cid,$flag)

{

	global $Itemid,$mainframe;
   
    $dt_user = new DT_User($cid[0]);

	$dt_user->save_field('attend',$flag);
	$_REQUEST['task'] = 'listregistrations';
	
    $get_str = http_build_query($_REQUEST);
	
	$mainframe->redirect("index2.php?".$get_str);
	
	$mainframe->redirect("index2.php?option=com_dtregister&task=listregistrations");

}

function getconditonField(){
  global $mainframe ; 
  
  $field = new Custom_field(JRequest::getVar('field_id',0));
  $field->read();
  
  $childs = $field->getchild();
  $selectionindex = JRequest::getVar('selection','');
  $not_remove =  JRequest::getVar('not_remove',array());
  if($field->type == 1){
     $selectionindex-- ;
  }
 
   $elements = array();
   $event = new Event(JRequest::getVar('eventId',0));
   $childjs = "" ;
   $user = unserialize(base64_decode(JRequest::getVar('obj','')));
   $evt_fields = $event->getAllFields();
   $remove_elements = array();
   $ordering =  array();
  foreach($childs as $key=>$child){
  
     $selection =  explode(',',$child->selection_values);
	$ordering[$child->id] = $child->ordering ;
	$selectionindex ;
	 if(in_array($selectionindex,$selection)){
	    $child = new Custom_field($child->id);
		$child->read();
		if(isset($evt_fields[$child->id])){
		   //$child->required = $evt_fields[$child->id]->required ;
		}
		$file = JPATH_SITE."/components/com_dtregister/view/field/field".$field->type.".php";
		  
		  if (!file_exists($file)) {
		     $file = JPATH_SITE."/components/com_dtregister/view/field/field.php";
		  }
		  $child->label = stripslashes($child->label).":";
		  if($child->required){
		    $child->label = $child->label." <span class='required'>&nbsp;&nbsp;*&nbsp;&nbsp;</span> ";
		  }
		  
		  $tpl = file_get_contents($file);
		  $constants = array('[label]','[value]','[description]');
		  $description =  (trim($child->description)!="")?JHTML::tooltip($child->description, '', 'tooltip.png', '', ''):'';
		  $replace  = array($child->label,$child->formhtml($user,$event,'adminForm',true),$description);
		  $childjs .= $child->childJs ;
		  $elements[$child->id] = str_replace($constants,$replace,$tpl);
		 //  print_r($elements);
		
	 }else{
	   $remove = true ;
	    foreach($selection as $val){
		    if(in_array($val,$not_remove)){
			   $remove = false;
			   break ;
			} 
		}
		
		if($remove){
		  $remove_elements[$child->id] = $child->id ;
		}
	 }
	 
    // print_r($child);
	 
  }
   $temp = $remove_elements ;
  
 foreach($remove_elements as $remove_element){
	  $rChilds = array();
	  
	  $field->findtree($remove_element,$rChilds);
	  
	  foreach($rChilds as $rchild){
		  if(!in_array($rchild->id,array_keys($elements)))
		  $temp[$rchild->id] = $rchild->id;
	  }
	
 }

 $remove_elements = $temp ;
  ob_start();
	 ?>
   
	 var elements = <?php echo json_encode($elements); ?>;
	  var remove_elements = <?php echo json_encode($remove_elements); ?>;
      var ordering = <?php echo json_encode($ordering); ?>;
     <?php
	 echo $childjs ;
	 $data =  ob_get_clean();
	 
	 echo str_replace("\n",' ',$data)."/*DTendScript*/";
	 die ;
  
}

?>
<div style="display:none">
<iframe name="fileupload">

</iframe>
</div>