<?php
/**
* @package		Contact Enhanced
* @copyright	Copyright (C) 2005 - 2010 Ideal.fok.com.br. All rights reserved.
 * @author     Douglas Machado {@link http://ideal.fok.com.br}
 * @author     Created on 28-Jul-09
 * @license		GNU/GPL, see license.txt
 * Contact Enhanced  is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * @license		GNU/GPL, see license.txt
 * Contact Enhanced  is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// Get the path of the configuration file
$fname = JPATH_COMPONENT.DS.'configuration.php';

// Config file exists?
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
if (!JFile::exists($fname)) {
	JError::raiseNotice('ERROR', 'Please set the Configuration first! It is not required but highly recommended');
	/// redirect to Configuration page
	JRequest::setVar('controller','config');
	JRequest::setVar('task','view');
	// Create config file
	JFile::copy('configuration-dist.php','configuration.php',JPATH_COMPONENT);
}

require_once( JPATH_COMPONENT.DS."configuration.php" );
$config	= new CEConfig();


require_once( JPATH_ROOT.DS.'components'.DS.'com_contact_enhanced'.DS."defines.php" );

// Set the table directory
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.COMPONENT_FOLDER.DS.'tables');

/*
 * Make sure the user is authorized to view this page
 */
$user = & JFactory::getUser();
if (!$user->authorize( 'com_contact', 'manage' )) {
	$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') );
}
$lang =& JFactory::getLanguage();
$lang->load('com_contact');
// The Extra field labels are translated in the Front-end language file
$lang->load('com_contact_enhanced',JPATH_SITE);

// Require the base controller
require_once (JPATH_COMPONENT.DS.'controller.php');
require_once( JPATH_ROOT.DS.'components'.DS.COMPONENT_FOLDER.DS.'helper'.DS."helper.php" );

$controller	= new Contact_EnhancedsController();

// Require specific controller if requested
if($controllerName = JRequest::getVar('controller')) {
	require_once (JPATH_COMPONENT.DS.'controllers'.DS.$controllerName.'.php');
	// Create the controller
	$classname	= 'Contact_EnhancedsController'.$controllerName;
	 
	$controller = new $classname( );
	
	// Perform the Request task
	$controller->execute( JRequest::getVar('task'));
	
	// Redirect if set by the controller
	$controller->redirect();
}else{
	require_once( JApplicationHelper::getPath( 'admin_html' ) );
	
	
	$task	= JRequest::getCmd('task');
	$id 	= JRequest::getVar('id', 0, 'get', 'int');
	$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
	JArrayHelper::toInteger($cid, array(0));
	
	switch ($task)
	{
		case 'element':
		case 'wizard':
			$controller->execute( $task );
			$controller->redirect();
			break;
			
		case 'doc' :
			HTML_contact::doc();
			break;
		case 'add' :
			editContact(false );
			break;
		case 'edit':
			editContact(true);
			break;
	
		case 'apply':
		case 'save':
		case 'save2new':
		case 'save2copy':
			saveContact( $task );
			break;
	
		case 'remove':
			removeContacts( $cid );
			break;
	
		case 'publish':
			changeContact( $cid, 1 );
			break;
	
		case 'unpublish':
			changeContact( $cid, 0 );
			break;
	
		case 'orderup':
			orderContacts( $cid[0], -1 );
			break;
	
		case 'orderdown':
			orderContacts( $cid[0], 1 );
			break;
	
		case 'accesspublic':
			changeAccess( $cid[0], 0 );
			break;
	
		case 'accessregistered':
			changeAccess( $cid[0], 1 );
			break;
	
		case 'accessspecial':
			changeAccess( $cid[0], 2 );
			break;
	
		case 'saveorder':
			saveOrder( $cid );
			break;
	
		case 'cancel':
			cancelContact();
			break;
		
		case 'showCF':
		case 'customfields': //CF = Custom Fields
			showCF($option);
			break;
		
		case 'editCF': //CF = Custom Field
			editCF( true );
			break;
		
		case 'newCF': //CF = Custom Field
			editCF(false);
			break;
		
		case 'saveCF':
			saveCF( $option );
			break;
		case 'applyCF':
			saveCF( $option );
			break;
	
		case 'removeCF':
			removeCF( $cid, $option );
			break;
	
		case 'CFpublish':
			changeCF( $cid, 1, $option );
			break;
	
		case 'CFunpublish':
			changeCF( $cid, 0, $option );
			break;
	
		case 'orderupCF':
			orderCF( intval( $cid[0] ), -1, $option );
			break;
	
		case 'orderdownCF':
			orderCF( intval( $cid[0] ), 1, $option );
			break;
	
		case 'cancelCF':
			cancelCF();
			break;
		
		case 'saveorderCF':
			saveOrderCF( $cid );
			break;
		case 'copyCF':
			copyCF( $cid );
			break;
		case 'copysaveCF':
			copysaveCF( $cid );
			break;
		case 'import':
			import();
			break;
		case 'exportCF':
			exportCF($cid);
			break;
		case 'importCF':
			importCF();
			break;
		case 'add_ce_form':
			addCEForm();
			break;
		default:
			showContacts( $option );
			break;
	}
}



/**
* List the records
* @param string The current GET/POST option
*/
function showContacts( $option )
{
	global $mainframe;
	
	$task	= JRequest::getCmd('task', 'showContacts');
	
	$db					=& JFactory::getDBO();
	$filter_order		= $mainframe->getUserStateFromRequest( $option.$task.'filter_order', 		'filter_order', 	'cd.ordering',	'cmd' );
	$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.$task.'filter_order_Dir',	'filter_order_Dir',	'',				'word' );
	$filter_state 		= $mainframe->getUserStateFromRequest( $option.$task.'filter_state', 		'filter_state', 	'',				'word' );
	$filter_catid 		= $mainframe->getUserStateFromRequest( $option.$task.'filter_catid', 		'filter_catid',		0,				'int' );
	$search 			= $mainframe->getUserStateFromRequest( $option.$task.'search', 				'search', 			'',				'string' );
	$search 			= JString::strtolower( $search );

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

	$where = array();

	if ( $search ) {
		$where[] = 'cd.name LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
	}
	if ( $filter_catid ) {
		$where[] = 'cd.catid = '.(int) $filter_catid;
	}
	if ( $filter_state ) {
		if ( $filter_state == 'P' ) {
			$where[] = 'cd.published = 1';
		} else if ($filter_state == 'U' ) {
			$where[] = 'cd.published = 0';
		}
	}

	$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
	if ($filter_order == 'cd.ordering'){
		$orderby 	= ' ORDER BY category, cd.ordering';
	} else {
		$orderby 	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', category, cd.ordering';
	}

	// get the total number of categories
	$query = 'SELECT count(*) '
	. ' FROM #__categories'
	. ' WHERE section = '.$db->Quote('com_contact_enhanced_details')
	;
	$db->setQuery( $query );
	//echo '<pre>'; print_r( $db->getQuery() ); echo '</pre>'; exit;
	$totalCategories = $db->loadResult();

	
	// get the total number of records
	$query = 'SELECT COUNT(*)'
	. ' FROM #__contact_enhanced_details AS cd'
	. $where
	;
	$db->setQuery( $query );
	//echo '<pre>'; print_r( $db->getQuery() ); echo '</pre>'; exit;
	$total = $db->loadResult();
	
	jimport('joomla.html.pagination');
	$pageNav = new JPagination( $total, $limitstart, $limit );

	// get the subset (based on limits) of required records
	$query = 'SELECT cd.*, cc.title AS category, u.name AS user, v.name as editor, g.name AS groupname'
	. ' FROM #__contact_enhanced_details AS cd'
	. ' LEFT JOIN #__groups AS g ON g.id = cd.access'
	. ' LEFT JOIN #__categories AS cc ON cc.id = cd.catid'
	. ' LEFT JOIN #__users AS u ON u.id = cd.user_id'
	. ' LEFT JOIN #__users AS v ON v.id = cd.checked_out'
	. $where
	. $orderby
	;
	$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	$rows = $db->loadObjectList();
	//echo '<pre>'; print_r( $db->stderr(true) ); echo '</pre>'; exit;

	// build list of categories
	$javascript = 'onchange="document.searchForm.submit();"';
	$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_contact_enhanced_details', intval( $filter_catid ), $javascript );

	// state filter
	$lists['state']	= JHTML::_('grid.state',  $filter_state );

	// table ordering
	$lists['order_Dir']	= $filter_order_Dir;
	$lists['order']		= $filter_order;

	// search filter
	$lists['search']= $search;

	HTML_contact::showcontacts( $rows, $pageNav, $option, $lists,$totalCategories );
}

/**
* Creates a new or edits and existing user record
* @param int The id of the record, 0 if a new entry
* @param string The current GET/POST option
*/
function editContact($edit )
{
	$db		=& JFactory::getDBO();
	$user 	=& JFactory::getUser();

	$cid 	= JRequest::getVar('cid', array(0), '', 'array');
	$option = JRequest::getCmd('option');
	
	$config	= new CEConfig();

	JArrayHelper::toInteger($cid, array(0));

	$row =& JTable::getInstance('contact', 'Table');
	// load the row from the db table
	if($edit)
	$row->load( $cid[0] );

	if ($edit) {
		// do stuff for existing records
		$row->checkout($user->get('id'));
	} else {
		// do stuff for new records
		$row->imagepos 	= 'top';
		$row->ordering 	= 0;
		$row->published = 1;
	}
	$lists = array();

	// build the html select list for ordering
	$query = 'SELECT ordering AS value, name AS text'
	. ' FROM #__contact_enhanced_details'
	. ' WHERE published >= 0'
	. ' AND catid = '.(int) $row->catid
	. ' ORDER BY ordering'
	;
	if($edit)
		$lists['ordering'] 			= JHTML::_('list.specificordering',  $row, $cid[0], $query );
	else
		$lists['ordering'] 			= JHTML::_('list.specificordering',  $row, '', $query );

	// build list of users
	$lists['user_id'] 			= JHTML::_('list.users',  'user_id', $row->user_id, 1, NULL, 'name', 0 );
	// build list of categories
	$lists['catid'] 			= JHTML::_('list.category',  'catid', 'com_contact_enhanced_details', intval( $row->catid ) );
	// build the html select list for images
	$javascript = "onchange=\"javascript:if (document.forms.adminForm.image.options[selectedIndex].value!='') {document.imagelib.src='../$config->image_path' + document.forms.adminForm.image.options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
	$lists['image'] 			= JHTML::_('list.images',  'image', $row->image, $javascript, $config->image_path );
	// build the html select list for the group access
	$lists['access'] 			= JHTML::_('list.accesslevel',  $row );
	// build the html radio buttons for published
	$lists['published'] 		= JHTML::_('select.booleanlist',  'published', '', $row->published );
	// build the html radio buttons for default
	$lists['default_con'] 		= JHTML::_('select.booleanlist',  'default_con', '', $row->default_con );

	// get params definitions
	$file 	= JPATH_COMPONENT .'/contact_enhanced.xml';
	$params = new JParameter( $row->params, $file, 'component' );

	HTML_contact::editcontact( $row, $lists, $option, $params, $config );
}

/**
* Saves the record from an edit form submit
* @param string The current GET/POST option
*/
function saveContact( $task )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db		=& JFactory::getDBO();
	$row	=& JTable::getInstance('contact', 'Table');
	$post 	= JRequest::get( 'post' );
	$post['misc']	= JRequest::getVar('misc'	, '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['sidebar']= JRequest::getVar('sidebar', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_1']= JRequest::getVar('extra_field_1', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_2']= JRequest::getVar('extra_field_2', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_3']= JRequest::getVar('extra_field_3', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_4']= JRequest::getVar('extra_field_4', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_5']= JRequest::getVar('extra_field_5', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_6']= JRequest::getVar('extra_field_6', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_7']= JRequest::getVar('extra_field_7', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_8']= JRequest::getVar('extra_field_8', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_9']= JRequest::getVar('extra_field_9', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	$post['extra_field_10']= JRequest::getVar('extra_field_10', '', 'POST', 'string', JREQUEST_ALLOWHTML);
	
	
	
	if (!$row->bind( $post )) {
		JError::raiseError(500, $row->getError() );
	}
	// save params
	$params = JRequest::getVar( 'params', array(), 'post', 'array' );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		$row->params = implode( "\n", $txt );
	}

	// save to a copy, reset the primary key
	if ($task == 'save2copy') {
		$row->id = 0;
	}

	// pre-save checks
	if (!$row->check()) {
		JError::raiseError(500, $row->getError() );
	}

	// if new item, order last in appropriate group
	if (!$row->id) {
		$where = "catid = " . (int) $row->catid;
		$row->ordering = $row->getNextOrder( $where );
	}

	// save the changes
	if (!$row->store()) {
		JError::raiseError(500, $row->getError() );
	}
	$row->checkin();
	if ($row->default_con) {
		$query = 'UPDATE #__contact_enhanced_details'
		. ' SET default_con = 0'
		. ' WHERE id <> '. (int) $row->id
		. ' AND default_con = 1'
		;
		$db->setQuery( $query );
		$db->query();
	}

	switch ($task)
	{
		case 'apply':
		case 'save2copy':
			$msg	= JText::sprintf( 'Changes to X saved', 'Contact' );
			$link	= 'index.php?option=com_contact_enhanced&task=edit&cid[]='. $row->id .'';
			break;

		case 'save':
		default:
			$msg	= JText::_( 'Contact saved' );
			$link	= 'index.php?option=com_contact_enhanced';
			break;
	}

	$mainframe->redirect( $link, $msg );
}

/**
* Removes records
* @param array An array of id keys to remove
* @param string The current GET/POST option
*/
function removeContacts( &$cid )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db =& JFactory::getDBO();
	JArrayHelper::toInteger($cid);

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$query = 'DELETE FROM #__contact_enhanced_details'
		. ' WHERE id IN ( '. $cids .' )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			echo "<script> alert('".$db->getErrorMsg(true)."'); window.history.go(-1); </script>\n";
		}
	}

	$mainframe->redirect( "index.php?option=com_contact_enhanced" );
}

/**
* Changes the state of one or more content pages
* @param array An array of unique category id numbers
* @param integer 0 if unpublishing, 1 if publishing
* @param string The current option
*/
function changeContact( $cid=null, $state=0 )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db 	=& JFactory::getDBO();
	$user 	=& JFactory::getUser();
	JArrayHelper::toInteger($cid);

	if (count( $cid ) < 1) {
		$action = $state ? 'publish' : 'unpublish';
		JError::raiseError(500, JText::_( 'Select an item to' .$action, true ) );
	}

	$cids = implode( ',', $cid );

	$query = 'UPDATE #__contact_enhanced_details'
	. ' SET published = ' . (int) $state
	. ' WHERE id IN ( '. $cids .' )'
	. ' AND ( checked_out = 0 OR ( checked_out = '. (int) $user->get('id') .' ) )'
	;
	$db->setQuery( $query );
	if (!$db->query()) {
		JError::raiseError(500, $db->getErrorMsg() );
	}

	if (count( $cid ) == 1) {
		$row =& JTable::getInstance('contact', 'Table');
		$row->checkin( intval( $cid[0] ) );
	}

	$mainframe->redirect( 'index.php?option=com_contact_enhanced' );
}

/** JJC
* Moves the order of a record
* @param integer The increment to reorder by
*/
function orderContacts( $uid, $inc )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db =& JFactory::getDBO();

	$row =& JTable::getInstance('contact', 'Table');
	$row->load( $uid );
	$row->move( $inc, 'catid = '. (int) $row->catid .' AND published != 0' );

	$mainframe->redirect( 'index.php?option=com_contact_enhanced' );
}

/** PT
* Cancels editing and checks in the record
*/
function cancelContact()
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db =& JFactory::getDBO();
	$row =& JTable::getInstance('contact', 'Table');
	$row->bind( JRequest::get( 'post' ));
	$row->checkin();

	$mainframe->redirect('index.php?option=com_contact_enhanced');
}

/**
* changes the access level of a record
* @param integer The increment to reorder by
*/
function changeAccess( $id, $access  )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db =& JFactory::getDBO();

	$row =& JTable::getInstance('contact', 'Table');
	$row->load( $id );
	$row->access = $access;

	if ( !$row->check() ) {
		return $row->getError();
	}
	if ( !$row->store() ) {
		return $row->getError();
	}

	$mainframe->redirect( 'index.php?option=com_contact_enhanced' );
}

function saveOrder( &$cid )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db			=& JFactory::getDBO();
	$total		= count( $cid );
	$order 		= JRequest::getVar( 'order', array(0), 'post', 'array' );
	JArrayHelper::toInteger($order, array(0));

	$row =& JTable::getInstance('contact', 'Table');
	$groupings = array();

	// update ordering values
	for( $i=0; $i < $total; $i++ ) {
		$row->load( (int) $cid[$i] );
		// track categories
		$groupings[] = $row->catid;

		if ($row->ordering != $order[$i]) {
			$row->ordering = $order[$i];
			if (!$row->store()) {
				JError::raiseError(500, $db->getErrorMsg() );
			}
		}
	}

	// execute updateOrder for each parent group
	$groupings = array_unique( $groupings );
	foreach ($groupings as $group){
		$row->reorder('catid = '.(int) $group);
	}

	$msg 	= 'New ordering saved';
	$mainframe->redirect( 'index.php?option=com_contact_enhanced', $msg );
}


/**
* Creates a new or edits and existing user record
* @param int The id of the record, 0 if a new entry
* @param string The current GET/POST option
*/
function editCF( $edit ) {
	global $mainframe;

	$db		=& JFactory::getDBO();
	$user 	=& JFactory::getUser();
	$cid 	= JRequest::getVar('cid', array(0), '', 'array');
	$option = JRequest::getCmd('option');
	$cid 	= (int)$cid[0];
	
	$row =& JTable::getInstance('customfield', 'Table');
	
	// load the row from the db table
	if($edit){
		$row->load( $cid );
		
	}else{
		// do stuff for new records
		$row->ordering	= 0;
		$row->published	= 1;
		$row->required 	= 0;
	}
	//echo '<pre>'; print_r( $cid ); echo '</pre>'; exit;
	$lists = array();
	
	//$lists['catid'] = JHTML::_('list.category',  'catid', 'com_contact_enhanced_details', $row->catid );
	$lists['catid'] = categoryList('catid', 'com_contact_enhanced_details', $row->catid); //, ($row->iscore ? ' disabled' : '') 
	
	// build the html select list for ordering
	$query = "SELECT ordering AS value, name AS text"
	. "\n FROM #__contact_enhanced_cf"
	. "\n WHERE catid = ". (int) $row->catid
		. ($row->catid != 0 ? " \n OR catid = 0 " : '')
	. "\n ORDER BY ordering"
	;
	
	if($edit)
		$lists['ordering'] 		= JHTML::_('list.specificordering',  $row, $cid, $query );
	else
		$lists['ordering'] 		= JHTML::_('list.specificordering',  $row, '', $query );

	// build the html radio buttons for published
	$lists['published'] 		= JHTML::_('select.booleanlist',  'published', '', $row->published );
	// build the html radio buttons for required
	$lists['required']			= JHTML::_('select.booleanlist',  'required', '', $row->required );
	
	$types= array();
	
	//$types[] 					= JHTML::_('select.option', 'selectmultiple',JText::_('Select Multiple') ); // @todo: fix Validation problems
	$types[] 					= JHTML::_('select.option', 'text',			JText::_('Text Field') );
	$types[] 					= JHTML::_('select.option', 'checkbox', 	JText::_('Checkbox') );
	$types[] 					= JHTML::_('select.option', 'date', 		JText::_('Date') );
	$types[] 					= JHTML::_('select.option', 'daterange',	JText::_('Date Range') );
	$types[] 					= JHTML::_('select.option', 'freetext',		JText::_('Free Text') );
	$types[] 					= JHTML::_('select.option', 'hidden',		JText::_('Hidden input') );
	//$types[] 					= JHTML::_('select.option', 'file', 		JText::_('File') ); // @todo: fix Validation problems
	$types[] 					= JHTML::_('select.option', 'multiplefiles',JText::_('Multiple Files').' - '.JText::_('Beta') );
	$types[] 					= JHTML::_('select.option', 'multitext',	JText::_('Multitext') );
	$types[] 					= JHTML::_('select.option', 'number',		JText::_('Number') );
	$types[] 					= JHTML::_('select.option', 'numberrange', 	JText::_('Number Range') );
	$types[] 					= JHTML::_('select.option', 'password', 	JText::_('Password') );
	$types[] 					= JHTML::_('select.option', 'radiobutton',	JText::_('Radiobox') );
	
	$types[] 					= JHTML::_('select.option', 'selectlist',	JText::_('Selectlist') );
	$types[] 					= JHTML::_('select.option', 'sql'			,JText::_('SQL') );
	$types[] 					= JHTML::_('select.option', 'sqlmultiple'	,JText::_('SQL'). ' - '.JText::_('Multiple'));
	$types[] 					= JHTML::_('select.option', 'wysiwyg'		,JText::_('WYSIWYG HTML Editor') );
	
	$types[] 					= JHTML::_('select.optgroup', JText::_('One per Category') );
		$types[] 					= JHTML::_('select.option', 'name', 	JText::_('Name')	);
		$types[] 					= JHTML::_('select.option', 'surname', 	JText::_('Surname')	);
		$types[] 					= JHTML::_('select.option', 'subject', 	JText::_('Subject')	);
		$types[] 					= JHTML::_('select.option', 'email', 	JText::_('Email')	);
		$types[] 					= JHTML::_('select.option', 'recipient',JText::_('Select Recipient (to)') );
		$types[] 					= JHTML::_('select.option', 'username',	JText::_('Username'));
		
	
	$types[] 					= JHTML::_('select.optgroup', JText::_('Newsletters') );
		$types[] 					= JHTML::_('select.option', 'campaignmonitor', 	JText::_('CampaignMonitor')	);
	
	/**
	 * Added for compatibility
	 * @todo remove from newer versions
	 * @since 1.5.8.1 
	 */
	if($row->type == 'selectrecipient'){
		$row->type	= 'recipient';
	}
		
	$lists['field_type']		= JHTML::_('select.genericlist',   $types, 'type', 'class="inputbox" size="1" onchange="updateInputs(this.value)"', 'value', 'text', $row->type ); //.($row->iscore ? ' disabled' : '')
	
	$filepath	=  JPATH_BASE.DS.'components'.DS.COMPONENT_FOLDER.DS.'custom_fields'.DS;
	$customFieldparams = array();
	if( file_exists($filepath.$row->type.'.xml') ){
		$customFieldparams['custom']	= new JParameter( $row->params, $filepath.$row->type.'.xml');
	}
	$customFieldparams['default']	= new JParameter( $row->params, $filepath.'custom_fields.xml');
	//testArray($customFieldparams);

	HTML_customfield::editCF( $row, $lists, $option, $customFieldparams);
}


	/**
	* Form for copying item(s)
	**/
	function copyCF()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db			= & JFactory::getDBO();

		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$option		= JRequest::getCmd( 'option' );

		JArrayHelper::toInteger($cid);

		if (count($cid) < 1) {
			$msg = JText::_('Select an item to move');
			$mainframe->redirect('index.php?option='.$option.'&task=showCF', $msg, 'error');
		}

		//seperate cf ids
		$cids = implode(',', $cid);
		## CF query
		$query = 'SELECT cf.*' .
				' FROM #__contact_enhanced_cf AS cf' .
				' WHERE ( cf.id IN ( '. $cids .' ) )' .
				' ORDER BY cf.ordering';
		$db->setQuery($query);
		$items = $db->loadObjectList();

		## Category query
		$query = 'SELECT c.id AS `value`, c.title AS `text`' .
				' FROM #__categories AS c ' .
				' WHERE c.section = "com_contact_enhanced_details"' .
				' ORDER BY c.title';
		$db->setQuery($query);

		// Add a row for uncategorized contacts && I'm not sure if it will help it or not
		$uncat	= JHTML::_('select.option', '0', JText::_('All categories'));
		$rows	= $db->loadObjectList();
		// array_unshift($rows, $uncat); 
		// build the html select list
		$catList = JHTML::_('select.genericlist', $rows, 'category', 'class="inputbox" size="10"', 'value', 'text', NULL);

		HTML_customfield::copyCF($option, $cid, $catList, $items);
	}
	
	/**
	* saves Copies of Custom Fields
	**/
	function copysaveCF()
	{
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db			= & JFactory::getDBO();
		
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$option		= JRequest::getCmd( 'option' );

		JArrayHelper::toInteger($cid);

		$item	= null;
		$category = JRequest::getVar( 'category', 0, 'post', 'int' );


		if (!$category) {
			$mainframe->redirect('index.php?option='.$option.'&task=showCF', JText::_('An error has occurred'));
		}
		$name	= JRequest::getVar('name');
		
		foreach($cid as $id)
		{
			$row		=& JTable::getInstance('customfield', 'Table');

			// main query
			$query = 'SELECT *' .
					' FROM #__contact_enhanced_cf ' .
					' WHERE id = '.(int) $id;
			$db->setQuery($query, 0, 1);
			$item = $db->loadObject();

			// values loaded into array set for store
			$row->id						= NULL;
			$row->name						= ($name[$id] ? $name[$id] : $item->name);
			$row->label						= $item->label;
			$row->required					= $item->required;
			$row->type						= $item->type;
			$row->value						= $item->value;
			$row->ordering					= $item->ordering;
			$row->catid						= $category;
			$row->published					= $item->published;
			$row->attributes				= $item->attributes;
			$row->tooltip					= $item->tooltip;
			$row->iscore					= $item->iscore;
			$row->params					= $item->params;
		
			if (!$row->check()) {
				JError::raiseError( 500, $row->getError() );
				return false;
			}

			if (!$row->store()) {
				JError::raiseError( 500, $row->getError() );
				return false;
			}
			$row->reorder('catid='.(int) $row->catid.' AND published >= 0');
		}

		$msg = JText::sprintf('Item(s) successfully copied to Category');
		$mainframe->redirect('index.php?option='.$option.'&task=showCF', $msg);
	}
	
/**
* Saves the a custom field from an edit form submit
* @param string The current GET/POST option
*/
function saveCF( $option ) {
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db		=& JFactory::getDBO();
	$row	=& JTable::getInstance('customfield', 'Table');
	
	$task	= JRequest::getCmd('task');
	
	$post = JRequest::get( 'post' );
	$post['value']		= JRequest::getVar('value'	, '', 'POST', 'string', JREQUEST_ALLOWRAW);
	$post['tooltip']	= JRequest::getVar('tooltip', '', 'POST', 'string', JREQUEST_ALLOWRAW);
	$post['attributes']	= JRequest::getVar('attributes', '', 'POST', 'string', JREQUEST_ALLOWRAW);
	
	if($post['type'] == 'subject'){
		$post['iscore'] = 1;
	}
	
	if (!$row->bind( $post )) {
		JError::raiseError(500, $row->getError() );
	}
	
	// save params
	$params = JRequest::getVar( 'params', array(), 'post', 'array' );
	if (is_array( $params )) {
		//testArray($params);
		$txt = array();
		foreach ( $params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		$row->params = implode( "\n", $txt );
	}
	
	if (!$row->id) { 
		// if new item, order last in appropriate group
		$where = "catid = " . (int) $row->catid;
		$row->ordering = $row->getNextOrder( $where );
	}
	
	if($row->canInsert()){
		// save the changes
		if (!$row->store()) {
			JError::raiseError(500, $row->getError() );
		}
	}else{
		$task	= 'showError';
	}
	
	switch ($task)
	{
		case 'applyCF':
			$msg	= $msg	= JText::_( 'Custom Field saved' );
			$link	= 'index.php?option=com_contact_enhanced&task=editCF&cid[]='. $row->id .'';
			break;
		
		case 'showError':
			$msg	= JText::sprintf( 'Field NOT saved! Only one field type allowed per category',$row->type );
			$link	= 'index.php?option=com_contact_enhanced&task=editCF&cid[]='. $row->id .'';
			break;
		
		case 'save':
		default:
			$msg	= JText::_( 'Custom Field saved' );
			$link	= 'index.php?option=com_contact_enhanced&task=showCF';
			break;
	}

	$mainframe->redirect( $link, $msg );
	
}

/**
* List the Custom Fields
* @param string The current GET/POST option
*/
function showCF( $option ) {
	global $mainframe;
	
	$task	= JRequest::getCmd('task');
	
	$db					=& JFactory::getDBO();
	$filter_order		= $mainframe->getUserStateFromRequest( $option.$task.'filter_order', 		'filter_order', 	'cf.ordering',	'cmd' );
	$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.$task.'filter_order_Dir',	'filter_order_Dir','',			'word' );
	$filter_state 		= $mainframe->getUserStateFromRequest( $option.$task.'filter_state', 		'filter_state', 	'',				'word' );
	$filter_catid 		= $mainframe->getUserStateFromRequest( $option.$task.'filter_catid', 		'filter_catid',	0,				'int' );
	$search 			= $mainframe->getUserStateFromRequest( $option.$task.'cfSearch', 			'cfSearch', 			'',				'string' );
	$search 			= JString::strtolower( $search );

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

	$where = array();
	
	if ( $search ) {
		$where[] = 'cf.name LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
	}
	if ( $filter_catid ) {
		$where[] = "(cf.catid = ". (int) $filter_catid . " OR  cf.catid = 0 )";
	}
	if ( $filter_state ) {
		if ( $filter_state == 'P' ) {
			$where[] = 'cf.published = 1';
		} else if ($filter_state == 'U' ) {
			$where[] = 'cf.published = 0';
		}
	}

	$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
	if ($filter_order == 'cf.ordering'){
		$orderby 	= ' ORDER BY catid, cf.ordering';
	} else {
		$orderby 	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', catid, cf.ordering';
	}

	// get the total number of records
	$query = 'SELECT COUNT(*)'
	. ' FROM #__contact_enhanced_cf AS cf'
	. $where
	;
	$db->setQuery( $query );
	$total = $db->loadResult();

	jimport('joomla.html.pagination');
	$pageNav = new JPagination( $total, $limitstart, $limit );

	
	// get the subset (based on limits) of required records
	$query = 'SELECT cf.*, cc.title AS category '
	. ' FROM #__contact_enhanced_cf AS cf'
	. ' LEFT JOIN #__categories AS cc ON cc.id = cf.catid'
	. $where
	. $orderby
	;
	$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	//echo '<pre>'; print_r( $db->getQuery() ); echo '</pre>'; exit;
	$rows = $db->loadObjectList();

	// build list of categories
	$javascript = 'onchange="document.searchForm.submit();"';
	$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_contact_enhanced_details', intval( $filter_catid ), $javascript );

	// state filter
	//$lists['state']	= JHTML::_('grid.state',  $filter_state );
	$state	= array();
	$state[] = JHTML::_('select.option',  '', '- '. JText::_( 'Select State' ) .' -' );
	$state[] = JHTML::_('select.option',  'P', JText::_( "Published" ) );
	$state[] = JHTML::_('select.option',  'U', JText::_( "Unpublished" ) );

	$lists['state']	= JHTML::_('select.genericlist',   $state, 'filter_state', 'class="inputbox" size="1" '.$javascript, 'value', 'text', $filter_state );

	// table ordering
	$lists['order_Dir']	= $filter_order_Dir;
	$lists['order']		= $filter_order;

	// search filter
	$lists['search']= $search;
	HTML_customfield::showcf( $rows, $pageNav, $option, $lists );
}


function removeCF( &$cid, $option ) {
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db		=& JFactory::getDBO();
	$row	=& JTable::getInstance('customfield', 'Table');
	
	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$query = 'DELETE FROM #__contact_enhanced_cf'
		. ' WHERE id IN ( '. $cids .' )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			echo "<script> alert('".$db->getErrorMsg(true)."'); window.history.go(-1); </script>\n";
		}
	}

	$mainframe->redirect( "index.php?option=com_contact_enhanced&task=showCF" );
}
/**
* Changes the state of one or more custom Fields
* @param array An array of unique category id numbers
* @param integer 0 if unpublishing, 1 if publishing
* @param string The current option
*/
function changeCF( $cid=null, $state=0, $option ) {
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db 	=& JFactory::getDBO();
	$user 	=& JFactory::getUser();
	JArrayHelper::toInteger($cid);

	if (count( $cid ) < 1) {
		$action = $state ? 'publish' : 'unpublish';
		JError::raiseError(500, JText::_( 'Select an item to' .$action, true ) );
	}

	$cids = implode( ',', $cid );

	$query = 'UPDATE #__contact_enhanced_cf'
	. ' SET published = ' . (int) $state
	. ' WHERE id IN ( '. $cids .' )'
	;
	$db->setQuery( $query );
	if (!$db->query()) {
		JError::raiseError(500, $db->getErrorMsg() );
	}

	if (count( $cid ) == 1) {
		$row =& JTable::getInstance('customfield', 'Table');
		$row->checkin( intval( $cid[0] ) );
	}

	$mainframe->redirect( 'index.php?option=com_contact_enhanced&task=showCF' );
}


/** JJC
* Moves the order of a record
* @param integer The increment to reorder by
*/
function orderCF( $uid, $inc, $option ) {
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db =& JFactory::getDBO();

	$row =& JTable::getInstance('customfield', 'Table');
	$row->load( $uid );
	$row->move( $inc, 'catid = '. (int) $row->catid .' AND published != 0' );

	$mainframe->redirect( 'index.php?option=com_contact_enhanced&task=showCF' );

}


function cancelCF()
{
	global $mainframe;

	$mainframe->redirect('index.php?option=com_contact_enhanced&task=showCF');
}

function saveOrderCF( &$cid )
{
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db			=& JFactory::getDBO();
	$total		= count( $cid );
	$order 		= JRequest::getVar( 'order', array(0), 'post', 'array' );
	JArrayHelper::toInteger($order, array(0));

	$row =& JTable::getInstance('customfield', 'Table');
	$groupings = array();

	// update ordering values
	for( $i=0; $i < $total; $i++ ) {
		$row->load( (int) $cid[$i] );
		// track categories
		$groupings[] = $row->catid;

		if ($row->ordering != $order[$i]) {
			$row->ordering = $order[$i];
			if (!$row->store()) {
				JError::raiseError(500, $db->getErrorMsg() );
			}
		}
	}

	// execute updateOrder for each parent group
	$groupings = array_unique( $groupings );
	foreach ($groupings as $group){
		$row->reorder('catid = '.(int) $group);
	}

	$msg 	= JText::_('New ordering saved');
	$mainframe->redirect( 'index.php?option=com_contact_enhanced&task=showCF', $msg );
}

/**
* Select list of active categories for components
*/
function categoryList( $name, $section, $active = NULL, $javascript = NULL, $order = 'ordering', $size = 1, $sel_cat = 1 )
{
	$db =& JFactory::getDBO();

	$query = 'SELECT id AS value, title AS text'
	. ' FROM #__categories'
	. ' WHERE section = '.$db->Quote($section)
	. ' AND published = 1'
	. ' ORDER BY '. $order
	;
	$db->setQuery( $query );
	if ( $sel_cat ) {
		$categories[]	= JHTML::_('select.option',  '', '- '. 	JText::_( 'Select a Category' ) .' -' );
		$categories[]	= JHTML::_('select.option',  '0', 		JText::_( 'All categories' ));
		$categories 	= array_merge( $categories, $db->loadObjectList() );
	} else {
		$categories = $db->loadObjectList();
	}

	return JHTML::_('select.genericlist',   $categories, $name, 'class="inputbox" size="'. $size .'" '. $javascript, 'value', 'text', $active );
}

function import() {
		global $mainframe;
		$db			= & JFactory::getDBO();
		$sql = "SELECT * FROM #__categories" .
		" WHERE section = 'com_contact_details'";
		
		$db->setQuery($sql);
		$categs = $db->loadObjectList();
		if($db->getErrorNum()) {
			$mainframe->redirect( 'index.php?option=com_contact_enhanced', $db->getErrorMsg() );
		}
		foreach($categs as $cat) {
			$vals = array();
			$vals[] = $cat->parent_id;
			$vals[] = $db->Quote($cat->title);
			$vals[] = $db->Quote($cat->name);
			$vals[] = $db->Quote($cat->alias);
			$vals[] = $db->Quote($cat->image);
			$vals[] = $db->Quote('com_contact_enhanced_details');
			$vals[] = $db->Quote($cat->image_position);
			$vals[] = $db->Quote($cat->description);
			$vals[] = $cat->published;
			$vals[] = $db->Quote($cat->checked_out);
			$vals[] = $db->Quote($cat->checked_out_time);
			$vals[] = $db->Quote($cat->editor);
			$vals[] = $cat->ordering;
			$vals[] = $cat->access;
			$vals[] = $cat->count;
			$vals[] = $db->Quote($cat->params);
			
			$sql = "INSERT INTO #__categories" .
			" (parent_id, title, name, alias, image, section, image_position, description, published, checked_out, checked_out_time, editor, ordering, access, count, params)" .
			" VALUES (" . implode(',', $vals) . ")";
			$db->setQuery($sql);
			if(!$db->query()) {
				$mainframe->redirect( 'index.php?option=com_contact_enhanced', $db->getErrorMsg() );
			}
			$catid = $db->insertid();
			
			$sql = "SELECT * FROM #__contact_details " .
			"WHERE catid=" . $cat->id;
			$db->setQuery($sql);
			$contacts = $db->loadObjectList();
			if($db->getErrorNum()) {
				$mainframe->redirect( 'index.php?option=com_contact_enhanced', $db->getErrorMsg() );
			}
			if(count($contacts)) {
				foreach($contacts as $cont) {
					$vals = array();
					$vals[] = $db->Quote($cont->name);
					$vals[] = $db->Quote($cont->alias);
					$vals[] = $db->Quote($cont->con_position);
					$vals[] = $db->Quote($cont->address);
					$vals[] = $db->Quote($cont->suburb);
					$vals[] = $db->Quote($cont->state);
					$vals[] = $db->Quote($cont->country);
					$vals[] = $db->Quote($cont->postcode);
					$vals[] = $db->Quote($cont->telephone);
					$vals[] = $db->Quote($cont->fax);
					$vals[] = $db->Quote($cont->misc);
					$vals[] = $db->Quote($cont->image);
					$vals[] = $db->Quote($cont->imagepos);
					$vals[] = $db->Quote($cont->email_to);
					$vals[] = $cont->default_con;
					$vals[] = $cont->published;
					$vals[] = $db->Quote($cont->checked_out);
					$vals[] = $db->Quote($cont->checked_out_time);
					$vals[] = $cont->ordering;
					$vals[] = $db->Quote($cont->params);
					$vals[] = $cont->user_id;
					$vals[] = $catid;
					$vals[] = $cont->access;
					$vals[] = $db->Quote($cont->mobile);
					$vals[] = $db->Quote($cont->webpage);
					
					$sql = "INSERT INTO #__contact_enhanced_details" .
					" (name, alias, con_position, address, suburb, state, country, postcode, telephone, fax, misc, image, imagepos, email_to, " .
					"default_con, published, checked_out, checked_out_time, ordering, params, user_id, catid, access, mobile, webpage) " .
					"VALUES (" . implode(',', $vals) . ")";
					$db->setQuery($sql);
					if(!$db->query()) {
						$mainframe->redirect( 'index.php?option=com_contact_enhanced', $db->getErrorMsg() );
					}
				}
			}
		}
		$mainframe->redirect( 'index.php?option=com_contact_enhanced', JText::_('Contacts imported successfully') );
	}
	
function exportCF($cid){
	require_once(JPATH_COMPONENT.DS.'helpers'.DS.'export.php');
	ceExport::customFields($cid);
}
function importCF(){
	global $mainframe;
	require_once(JPATH_COMPONENT.DS.'helpers'.DS.'import.php');
	
	$sql_file	= JRequest::getVar( 'sql_file', false, 'files' );
	$link = 'index.php?option=com_contact_enhanced&task=showCF';
	$content	= ceImport::getFileContent('',$sql_file['tmp_name']);
	
	if( $content ){
		$db		=& JFactory::getDBO();
		$table	= $db->replacePrefix('#__contact_enhanced');
		$result	= ceImport::executeQuery($content, '','', 'INSERT INTO '.$table);
		if($result){
			$mainframe->redirect($link,JText::_( 'Custom fields imported successfully!' ));
		}
	}
}

function testArray($array, $exit=true){
	echo '<pre>';
	print_r($array);
	echo '</pre>';
	if($exit) exit;
}

function addCEForm() {
	$doc =& JFactory::getDocument();
	$doc->addStyleSheet( JURI::base() . 'components/com_contact_enhanced/assets/css/contact_enhanced.css');
        
	$eName	= JRequest::getVar('e_name');
	$eName	= preg_replace( '#[^A-Z0-9\-\_\[\]]#i', '', $eName );
		
	$db = &JFactory::getDBO();

	$query = 'SELECT a.id as value, CONCAT( a.name, " - ",a.con_position ) AS text, a.catid '
	. ' FROM #__contact_enhanced_details AS a'
	. ' INNER JOIN #__categories AS c ON a.catid = c.id'
	. ' WHERE a.published = 1'
	. ' AND c.published = 1'
	. ' ORDER BY a.catid, a.name'
	;
	$db->setQuery( $query );
	$options= $db->loadObjectList( );
	$label	= array(JHTML::_('select.option',  '0', JText::_( 'Select Contact' ) ));
	$options= array_merge($label,$options);
	
	$html	= '<h1 class="componentheading">'.JText::_('CE_PLUGIN_EDITOR_ADD_FORM').'</h1>';
	$html	.= '<div>'.JText::_('CE_PLUGIN_EDITOR_ADD_FORM_DESC').'</div><br />';
	
	$onchange	= " onchange=\"window.parent.jInsertEditorText('{loadcontact '+this.value+'} ', '".$eName."');
		window.parent.document.getElementById('sbox-window').close();\"";
	$html	.= JHTML::_('select.genericlist',  $options, 'contact_id', 'class="inputbox"'.$onchange);
	$html	.= '<br /><br /><br />';
	echo $html;
}

echo '<div class="footer" style="text-align:center;margin:15px;color:#708090;clear:both">'
		. 'Contact Enhanced - Version: '.CE_VERSION
		. '<br />'
		. 'Powered by: <a href="http://ideal.fok.com.br" target="_blank" >Ideal Custom Joomla Development</a>'
		. '</div>';
