 <?php
/**
 * @version $Id$
 * @package    contactEnhanced
 * @author     Douglas Machado {@link http://ideal.fok.com.br/}
 * @author     Created on 08-Jul-2009
 */

//--No direct access
defined('_JEXEC') or die('=;)');

$mainframe->registerEvent( 'onPrepareContent', 'plgContentContactEnhanced' );
 
/**
 * This plugin will trigger the string {triggercontactEnhanced}
 *
 * @param $row
 * @param $params
 * @param $page
 * 
 * @return void
 */
function plgContentContactEnhanced( &$row, &$params, $page=0 )
{
	if( ! strpos($row->text, 'loadcontact '))
	{
		//--The tag is not found in content - abort..
		return;
	}
	
	// Get plugin info
	$plugin =& JPluginHelper::getPlugin('content', 'contactenhanced');

 	// expression to search for
 	$regex = '/{loadcontact\s*.*?}/i';

 	$pluginParams = new JParameter( $plugin->params );

	// check whether plugin has been unpublished
	if ( !$pluginParams->get( 'enabled', 1 ) ) {
		$row->text = preg_replace( $regex, '', $row->text );
		return true;
	}

 	// find all instances of plugin and put in $matches
	preg_match_all( $regex, $row->text, $matches );

	// Number of plugins
 	$count = count( $matches[0] );

 	// plugin only processes if there are any instances of the plugin in the text
 	if ( $count ) {
 		plgContentProcessContacts( $row, $matches, $count, $regex, $params );
	}
}//function


function plgContentProcessContacts ( &$row, &$matches, $count, $regex,&$params )
{
 	$lang =& JFactory::getLanguage();
	$lang->load('com_contact_enhanced');
	
	$plugin =& JPluginHelper::getPlugin('content', 'contactenhanced');
 	$pluginParams = new JParameter( $plugin->params );
	
	for ( $i=0; $i < $count; $i++ )
	{
 		$contactId = str_replace( 'loadcontact', '', $matches[0][$i] );
 		$contactId = str_replace( '{', '', $contactId );
 		$contactId = str_replace( '}', '', $contactId );
 		$contactId = trim( $contactId );

 		//echo '<pre>'; print_r($pluginParams); echo '</pre>'; exit;
 		$contact= plgContentLoadContact( $contactId,$pluginParams,$row );
 		$row->text 	= str_replace($matches[0][$i], $contact, $row->text );
 	}

  	// removes tags without matching module positions
	$row->text = preg_replace( $regex, '', $row->text );
}

function plgContentLoadContact( &$contactId,&$pluginParams,&$row)
{
	require_once(JPATH_BASE .DS.'administrator'.DS.'components'.DS.'com_contact_enhanced'.DS.'configuration.php');
	$config	= new CEConfig();
	require_once(JPATH_BASE .DS.'components'.DS.'com_contact_enhanced'.DS.'defines.php');
	require_once(JPATH_BASE .DS.'components'.DS.'com_contact_enhanced'.DS.'models'.DS.'contact.php');
	require_once(JPATH_BASE .DS.'components'.DS.'com_contact_enhanced'.DS.'customFields.class.php');
	require_once(JPATH_BASE .DS.'components'.DS.'com_contact_enhanced'.DS.'helper'.DS.'helper.php');
	global $mainframe;
	
	$ceObj			= new JObject();	
	$ceObj->params	= &$mainframe->getParams('com_contact_enhanced');
	$ceObj->user	= &JFactory::getUser();
	$document		= & JFactory::getDocument();
	
	if($pluginParams->get('contact_postion')){
		$style	= ' style="float:'.$pluginParams->get('contact_postion').'; '.$pluginParams->get('contact_layer_style').'" ';
	}else{
		$style	= '';
	}

	$model		= new ContactModelContact();

	// query options
	$options['id']		= $contactId;
	$options['aid']		= $ceObj->user->get('aid', 0);

	$ceObj->contact		= $model->getContact( $options );
	if(!is_object($ceObj->contact)){
		return JText::sprintf('CE_PLUGIN_THERE_IS_NO_CONTACT_ID',$contactId);
	}
	$ceObj->customfields= $model->getCustomFields( $ceObj->contact->catid);
//echo 'Test: <pre>'; print_r($ceObj->contact); exit;	 
	// Adds parameter handling
	$ceObj->contact->params = new JParameter($ceObj->contact->params);

	$ceObj->params->merge($ceObj->contact->params);
	$ceObj->params->set('plugin_active',1);
	
	JHTML::_('behavior.mootools');
	JHTML::_('behavior.tooltip');
	
	
	
	$html 	= '<div class="ce-contact_email" '.$style.'>';
	
	// In case form is sent and plugin setup to show thank you message when submitted
	if(JRequest::getVar( 'msgsent' ) AND $pluginParams->get('after_submit') == 'thankyoumessage'){
 			$html 	.= '<div class="ce-plugin-message">'.JText::_('PLUGIN_THANK_YOU_MESSAGE').'</div>';
 			$html 	.= '</div>';
 			return $html;
	}
	
	if($pluginParams->get('after_submit') != 'global'){
		$router	= $mainframe->getRouter();
		$vars	= $router->getVars(); 
		$vars['msgsent']	= 1;
		$ceObj->params->set('return_url','index.php?'.JURI::buildQuery($vars));
	}
	$html	.=ceHelper::loadForm($ceObj);
	$html	.= '</div>';
	return $html;
}

function plgContentLoadCustomFields(&$customfields,&$pparams){
		global $mainframe;
		$html = '';
		
		foreach($customfields as $customfield){
			$field = "mFieldType_".$customfield['type'];
			$customfield['params']	= new JParameter($customfield['params']);
			$customfield['params']->merge($pparams);
			$pparams->set('plugin_active',1);
			$cf = new $field($customfield,$pparams);
			if($cf->published AND $cf->type != 'hidden' AND $cf->type != 'freetext'){
				$html .= '<div class="ce-cf-container" id="ce-cf-container-'.$customfield['id'].'">';
				$label= '<label'.($cf->isRequired() ? '  class="cf-label requiredField" ':'cf-label').' for="'.$cf->getInputName(false).'">'.JText::_( $cf->getInputFieldName() ).($cf->isRequired() ? ' *':'').'</label><br />';
				if($cf->tooltip){
					$html .= '<span class="editlinktip hasTip" title="'. JText::_( $cf->tooltip ). '">'
						. $label
						. '</span>';
				}else{
					$html .= $label;
				}	
			}
			$html .= $cf->getInputHTML();
			if($cf->published  AND $cf->type != 'hidden' AND $cf->type != 'freetext'){
				$html .= '</div>';
			}
		}
		return $html;
}
