<?php
/**
 * @package		Contact_Enhanced
 * @subpackage	Contact
 * @copyright	Copyright (C) 2006 - 2010 Ideal Custom Software Development
 * @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. 
 */
defined( '_JEXEC' ) or die( 'Restricted access' );

/**
 *
 * Abstract ceFieldType class.
 *
 */
class ceFieldType {
	var $id 	= null;
	var $name 	= null;
	var $value	= null;
	var $type 	= null;
	var $attributes = null;
	var $arrayFieldElements = null;
	var $allowHTML = false;
	var $params	= null;
	var $errors	= array();

	function ceFieldType( $data,&$params ) {
		if( !is_null($data) ){
			foreach( $data AS $key => $value ) {
				switch($key){
					case 'value':
						$this->arrayFieldElements = explode("|",$data->$key);
						$this->$key = $value;
						break;
					default:
						$this->$key = $value;
						break;
				}
			}
		}
		$this->params	= $params;
	}
	function getEmailOutput($delimiter= ', ',$format='text',$style=array('label'=>'','value'=>'')){
		if($format == 'html'){
			$html	= '<div class="ce-cf-container">';
				if( is_array($this->uservalue) ){
					$this->uservalue = implode($delimiter,$this->uservalue);
				}
				$html .= '<span style="'.$style['label'].'">'.JText::_($this->getInputFieldName()).'</span>' ;
				if($this->type == 'checkbox' OR $this->type == 'selectlist' OR $this->type == 'radiobutton'){
					$html .= '<span style="'.$style['value'].'">'.JText::_($this->uservalue).'</span>' ;
				}else{
					$html .= '<span style="'.$style['value'].'">'.($this->uservalue).'</span>' ;
				}
			$html	.= '</div>';
			return $html;	
		}else{
			if( is_array($this->uservalue) ){
				$this->uservalue = implode($delimiter,$this->uservalue);
			}
			return $this->getInputFieldName() .":\t ".JText::_($this->uservalue)."\n";	
		}
	}
	function getMySQLOutput(){
		if( is_array($this->uservalue) ){
			return implode('|',$this->uservalue);
		}else{
			return $this->uservalue;
		}
	}
	
	function isRequired() { 
		if($this->required){ return true;}else{ return false;}
	}

	function parseValue( $value ) { if ( is_array($value) ) { return ($this->allowHTML) ? implode("|",$value) : strip_tags(implode("|",$value));} else { $value = trim($value); return ($this->allowHTML) ? $value : strip_tags($value);}
	}
	function getFieldType() { return $this->type;}
	function getValue($arg=null) {
		$ce_cookie		= JRequest::getVar( 'ce_cookie',	'',	'cookie',  'none',JREQUEST_ALLOWHTML);
		//testArray($ce_cookie);
		if(is_null($arg)) {
			if( isset($ce_cookie[$this->getInputName('cookie')]) ){
				return $ce_cookie[$this->getInputName('cookie')];
			}elseif(isset($this->field_value)){
				return $this->field_value;
			}
			return $this->value;
		} elseif(is_numeric($arg)) {
			$values = explode('|',($this->value ? $this->value : (isset($this->field_value) ? $this->field_value : '') ));
			if(array_key_exists(($arg-1),$values)) {
				return trim($values[($arg-1)]);
			} else { return '';}
		} elseif($arg == 'session') {
			$session 		=& JFactory::getSession();
			$ce_session		= $session->get('ce_session', array());
			return $ce_session[$this->getInputName()];
		} elseif($arg) {
			$values = explode('|',$this->value);
			if(array_key_exists(($arg-1),$values)) {
				return trim($values[($arg-1)]);
			} else { return '';}
		} else { return '';}
		
	}
	function getInputHTML() { return '<input class="inputbox text_area cf-input-text '.($this->isRequired() ? ' required':'').'" type="text" name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"  value="' . htmlspecialchars($this->getValue()) . '" '.$this->attributes.' />'.'<br />';}
	function getName() { if( empty($this->name) ) { return 'cf' . $this->id;} else { return JText::_($this->name);}
	}
	function getInputFieldName($count=1) { if($count == 1) { return $this->getName();} elseif( $count <= $this->numOfInputFields ) { return $this->getName() . '_' . $count;}
	}
	function getInputName($count=1) {
		if($this->params->get('advanced-integration-name') AND $this->params->get('advanced',0) ){
			return trim($this->params->get('advanced-integration-name'));
		}
		return 'cf_'.$this->id;
	}
	function getLastError(){
		return end($this->errors);
	}
	function getOutput($view=1) { return $this->getValue();}
	function stripTags($value, $allowedTags='u,b,i,a,ul,li,pre,br,blockquote') { if(!empty($allowedTags)) { $tmp = explode(',',$allowedTags); array_walk($tmp,'trim'); $allowedTags = '<' . implode('><',$tmp) . '>';} else { $allowedTags = '';}
	return strip_tags( $value, $allowedTags );}
	function linkcreator( $matches ) { $url = 'http://'; $append = ''; if ( in_array(substr($matches[1],-1), array('.',')')) ) { $url .= substr($matches[1], 0, -1); $append = substr($matches[1],-1); # Prevent cutting off breaks <br />
	} elseif( substr($matches[1],-3) == '<br' ) { $url .= substr($matches[1], 0, -3); $append = substr($matches[1],-3);} elseif( substr($matches[1],-1) == '>' ) { $regex = '/<(.*?)>/i'; preg_match( $regex, $matches[1], $tags ); if( !empty($tags[1]) ) { $append = '<'.$tags[1].'>'; $url .= $matches[1]; $url = str_replace( $append, '', $url );}
	} else { $url .= $matches[1];}
	return '<a href="'.$url.'" target="_blank">'.$url.'</a>'.$append.' ';}
	function strlen_utf8($str) { return strlen(utf8_decode($this->utf8_html_entity_decode($str)));}
	function utf8_replaceEntity($result){ $value = intval($result[1]); $string = ''; $len = round(pow($value,1/8)); for($i=$len;$i>0;$i--){ $part = ($value AND (255>>2)) | pow(2,7); if ( $i == 1 ) $part |= 255<<(8-$len); $string = chr($part) . $string; $value >>= 6;}
	return $string;}
	function utf8_html_entity_decode($string) { return preg_replace_callback('/&#([0-9]+);/u',array($this,'utf8_replaceEntity'),$string);}
	function html_cutstr($str, $len) { if (!preg_match('/\&#[0-9]*;.*/i', $str)) { return substr($str,0,$len);}
	$chars = 0; $start = 0; for($i=0; $i < strlen($str); $i++) { if ($chars >= $len) { break;}
	$str_tmp = substr($str, $start, $i-$start); if (preg_match('/\&#[0-9]*;.*/i', $str_tmp)) { $chars++; $start = $i;}
	}
	$rVal = substr($str, 0, $start); if (strlen($str) > $start)
	return $rVal;}
	function html_substr($str, $start, $length = NULL) { if ($length === 0) return ''; if (strpos($str, '&') === false) { if ($length === NULL) return substr($str, $start); else return substr($str, $start, $length);}
	$chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE); $html_length = count($chars); if ( ($html_length === 0) or
	($start >= $html_length) or
	(isset($length) and ($length <= -$html_length)) ) { return '';}
	if ($start >= 0) { $real_start = $chars[$start][1];} else { $start = max($start,-$html_length); $real_start = $chars[$html_length+$start][1];}
	if (!isset($length)) { return substr($str, $real_start);} else if ($length > 0) { if ($start+$length >= $html_length) { return substr($str, $real_start);} else { return substr($str, $real_start, $chars[max($start,0)+$length][1] - $real_start);}
	} else { return substr($str, $real_start, $chars[$html_length+$length][1] - $real_start);}
	}
	function html_strlen($str) { $chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); return count($chars);}
	function getObjectVars() { var_dump(get_object_vars($this));}
	function getLabel($hideFieldTypes=null,$output='site'){
		if(!$hideFieldTypes){
			$hideFieldTypes	= array('hidden','freetext');
		}
		
		$html	= '';
		if($this->published AND !in_array($this->type,$hideFieldTypes) 
			AND !$this->params->get('hide_field') AND !$this->params->get('hide_field_label',0) ){
			$label= '<label class="cf-label'.($this->isRequired() ? ' requiredField':'').'" for="'.$this->getInputName(false).'">'.JText::_( $this->getInputFieldName() ).($this->isRequired() ? ' *':'').'</label>';
			if($this->tooltip){
				$html .= '<span class="editlinktip hasTip" title="'. JText::_( $this->tooltip ). '">'
					. $label
					. '</span>';
			}else{
				$html .= $label;
			}
		}
		return $html;
	}
	function getFieldHTML(){
		$html	= '';
		if($this->published AND $this->type != 'hidden' AND $this->type != 'freetext' OR (!$this->params->get('isAdmin')) ){
			$style	= ($this->params->get('hide_field',0) ? 'display:none;' : ''	);
			$html .= '<div class="ce-cf-container cf-type-'.$this->type.' ce-fltwidth-'.round($this->params->get('field-width',100)).'" id="ce-cf-container-'.$this->id.'" style="'.$style.'">';
			$html .= $this->getLabel();
			$html .= $this->getInputHTML();
			$html .= '</div>';
		}else{
			$html .= $this->getLabel();
			$html .= $this->getInputHTML();
		}
		if($this->params->get('isAdmin')){
			$html .= $this->getRecordedFieldId();
		}
		return $html;
	}
	function getRecordedFieldId(){
		return '<input type="hidden" name="'.$this->getInputName().'_id" value="'.$this->field_id.'" />';
	}
	function getValidationScript() {
		return '';
	}
}
class ceFieldType_text extends ceFieldType {
	function getInputHTML() { 
		$class	= '';
		$alt	= '';
		$js		= '';
		$title	= '';
		if($this->params->get('validation') == 'iMask' AND $this->params->get('mask_mask') ){
			$class	= ' iMask';
			
			$alt	= "{type:'".		$this->params->get('mask_type','fixed')."',
						mask:'".		$this->params->get('mask_mask')."',
						stripMask:".	$this->params->get('mask_stripMask','true')."}";
			$doc	=& JFactory::getDocument();
			$doc->addScript(JURI::root().'components/'.COMPONENT_FOLDER.'/assets/js/imask/iMask.js');
			$title	= ' '.JText::_('Format').': '.$this->params->get('mask_mask');
		}elseif($this->params->get('validation')){
			$js	= ' onkeydown="return '.$this->params->get('validation').'(event);" ';
		}
		 
		return '<input class="inputbox cf-input-text text_area'.($this->isRequired() ? ' required':'').$class.'" type="text" 
				name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"  
				value="' . htmlspecialchars($this->getValue()) . '" '.$this->attributes.'
				alt="'.$alt.'" 
				title="'.$title.'" 
				'.$js.' />'.'<br />';
	}
}
class ceFieldType_multitext extends ceFieldType {
	function getInputHTML() {
		$html = '<textarea name="' . $this->getInputName() . '" id="' . $this->getInputName() . '" class="inputbox text_area'.($this->isRequired() ? ' required':'').'" '.($this->attributes ? $this->attributes : ' cols="40" rows="8" ' ).' >' . $this->getValue() . '</textarea>';
		return $html;
	}
}
class ceFieldType_weblink extends ceFieldType {
	function getInputHTML() {
		$showGo = $this->getParam('showGo',0);
		$html	= '<input class="inputbox  cf-input-text  text_area'.($this->isRequired() ? ' required':'').'" type="text" name="' . $this->getInputName() . '" id="' . $this->getInputName() . '" size="' . $this->getSize() . '" value="' . htmlspecialchars($this->getValue()) . '" />'; if($showGo) { $html .= '&nbsp;'; $html .= '<input type="button" class="button" onclick=\''; $html .= 'javascript:window.open("index3.php?option=com_mtree&task=openurl&url="+escape(document.getElementById("' . $this->getInputName() . '").value))\''; $html .= 'value="' . $_MT_LANG->GO . '"  '.$this->attributes.' />';}
		return $html;
	}

}
class ceFieldType_selectlist extends ceFieldType{
	function getInputHTML() {
		$javascript	= '';
		if($this->params->get('chain_select') AND $this->params->get('chain_select-enabled-option')){
			$javascript	= "onchange=\"JsonSelect.updateSelect('".$this->params->get('chain_select-enabled-option')."',this,'".JURI::root()."');\"";
			$doc	=& JFactory::getDocument();
			$doc->addScript(JURI::root().'components/com_contact_enhanced/assets/js/chainSelectList.js');
		}
		
		$html = '<select name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"'
				.	$javascript. ' class="inputbox text_area'.($this->isRequired() ? ' required':'').'" '.$this->attributes.' >';
		$html .= '<option value="">'.JText::_($this->params->get('first_option', 'Please select one')).'</option>';
		foreach($this->arrayFieldElements AS $fieldElement) {
			if(strpos($fieldElement, '::') > 0){
				$fieldElement = explode('::', $fieldElement);
			}else{
				$fieldElement = array($fieldElement,$fieldElement);
			}
			$html .= '<option value="'.JText::_($fieldElement[0]).'"';
			if( $fieldElement[0] == $this->getValue() ) {
				$html .= ' selected';
			}
			$html .= '>' . JText::_($fieldElement[1]) . '</option>';
		}
		$html .= '</select>'; 
		return $html;
	}
}
/**
 * @author douglas
 * @deprecated
 */
class ceFieldType_selectrecipient extends ceFieldType_recipient{
	
}
/**
 * Gets a recipient select list
 * @author douglas
 * @since 1.5.8.1
 */
class ceFieldType_recipient extends ceFieldType_selectlist{
	function getInputName(){
		return 'recipient';
	}
	
	function getInputHTML() {
		$javascript	= '';
		if($this->params->get('chain_select') AND $this->params->get('chain_select-enabled-option')){
			$javascript	= "onchange=\"JsonSelect.updateSelect('".$this->params->get('chain_select-enabled-option')."',this,'".JURI::root()."');\"";
			$doc	=& JFactory::getDocument();
			$doc->addScript(JURI::root().'components/com_contact_enhanced/assets/js/chainSelectList.js');
		}
		
		$html = '<select name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"'
				.	$javascript. ' class="inputbox text_area'.($this->isRequired() ? ' required':'').'" '.$this->attributes.' >';
		$html .= '<option value="">'.JText::_($this->params->get('first_option', 'Please select one')).'</option>';
		foreach($this->arrayFieldElements AS $fieldElement) {
			if(strpos($fieldElement, '::') > 0){
				$fieldElement = explode('::', $fieldElement);
				$fieldElement = array($fieldElement[1],$fieldElement[1]);
			}else{
				$fieldElement = array($fieldElement,$fieldElement);
			}
			$html .= '<option value="'.JText::_(trim($fieldElement[0])).'"';
			if( $fieldElement[0] == $this->getValue() ) {
				$html .= ' selected';
			}
			$html .= '>' . JText::_(trim($fieldElement[1])) . '</option>';
		}
		$html .= '</select>'; 
		return $html;
	}
	/**
	 * Used to get the value of a submitted field
	 * @param string	$text
	 */
	function getSelectedValue($text) {
		foreach($this->arrayFieldElements AS $fieldElement) {
			if(strpos($fieldElement, $text) > 0){
				$fieldElement = explode('::', $fieldElement);
				return trim($fieldElement[0]);
			}
		}
		return false;
	}
}
class ceFieldType_selectmultiple extends ceFieldType {
	function getInputHTML() {
		$html = '<select name="' . $this->getInputName() . '" id="' . $this->getInputName() . '" class="inputbox text_area'.($this->isRequired() ? ' required':'').'"';
		$html .= ' multiple size="'.( count($this->arrayFieldElements) > 8 ? 8 : count($this->arrayFieldElements) ).'"';
		$html .= ' '.$this->attributes.' ';
		$html .= '>'; $html .= '<option value=""></option>'; if( $this->getValue() <> '' ) { $selectmultiple_values = explode("|",$this->getValue());} else { $selectmultiple_values = array();}
		foreach($this->arrayFieldElements AS $fieldElement) { $html .= '<option value="'.$fieldElement.'"'; if(count($selectmultiple_values)>0 && in_array($fieldElement,$selectmultiple_values)) { $html .= ' selected';}
		$html .= '>' . $fieldElement . '</option>';}
		$html .= '</select>';
		return $html;
	}
}
class ceFieldType_radiobutton extends ceFieldType {
	var $_selectCounter	= 0;
	function getInputHTML() {
		$javascript	= '';
		if($this->params->get('chain_select') AND $this->params->get('chain_select-enabled-option')){
			$javascript	= " onclick=\"JsonSelect.updateSelect('".$this->params->get('chain_select-enabled-option')."',this,'".JURI::root()."');\" ";
			$doc	=& JFactory::getDocument();
			$doc->addScript(JURI::root().'components/com_contact_enhanced/assets/js/chainSelectList.js');
		}
		$html 	= '';
		$cols	= $this->params->get('number_of_columns',1);
		$width	= number_format( (100/$cols), 1);
		$i = 0;
		$html .= '<div class="ce-radiobox-container">';
		$this->_selectCounter = 0;
		
		$valueArray	= array();
		if(isset($this->field_value)){
			$valueArray	= (explode(", ", $this->field_value));

		}
		
		foreach($this->arrayFieldElements AS $fieldElement) {
			if(!empty($fieldElement)) {
				$html .= '<div style="width:'.$width.'%;float:left">';
				$html .= '<input type="radio" class="cf-input-radio '.($this->isRequired() ? 'required validate-radio':'').'" name="' . $this->getInputName() . '" value="'.$fieldElement.'" id="' . $this->getInputName() . '_' . $i . '" ';
				if( $fieldElement == $this->getValue()  
						OR in_array($fieldElement, $valueArray)  === true
						OR ($this->_selectCounter== 0 AND $this->params->get('radiobutton_first_selected', 0)) ) { $html .= 'checked ';}
				$html .= ' '.$this->attributes.' '.$javascript;
				$html .= '/><label for="' . $this->getInputName() . '_' . $i . '">'.JText::_($fieldElement).'</label>';
				$html .= '</div>'; $i++;
				$this->_selectCounter++;
			}
		}
		$html .= '</div>';
		return $html;
	}
	function getRecordedFieldId(){
		return '<input type="hidden" name="'.parent::getInputName().'_id" value="'.$this->field_id.'" />';
	}
}
class ceFieldType_checkbox extends ceFieldType{
	var $_selectCounter	= 0;
	
	function ceFieldType_checkbox( $data,&$params ) {
		if( !is_null($data) ){
			foreach( $data AS $key => $value ) {
				switch($key){
					case 'value':
						$this->arrayFieldElements = explode("|",$data->$key);
						$this->$key = '';
						break;
					default:
						$this->$key = $value;
						break;
				}
			}
		}
		$this->params	= $params;
	}
	
	function getInputHTML() {
		$this->_selectCounter = 0;
		$cols	= $this->params->get('number_of_columns',1);
		$width	= number_format( (100/$cols), 1);
		$html = '';
		$html .= '<div class="ce-checkbox-container">';
		if( $this->getValue() <> '' ) {
			$checkbox_values = explode("|",$this->getValue());
		} else {
			$checkbox_values = array();
		}
		
		$valueArray	= array();
		if(isset($this->field_value)){
			$valueArray	= (explode(", ", $this->field_value));

		}
		
		$classid =	JUtility::getHash(microtime());
		$html .=	$this->getSelectAllLink($classid);
		
		foreach($this->arrayFieldElements AS $fieldElement) {
			$html .= '<div style="width:'.$width.'%;float:left">';
			$html .= '<input type="checkbox" class="cf-input-checkbox check-me-'.$classid.($this->isRequired() ? ' required validate-checkbox':'').'" name="' . $this->getInputName() . '" value="'.$fieldElement.'" id="' . $this->getInputName() . '_' . $this->_selectCounter . '" ';
			if( $fieldElement == $this->getValue() 
				OR in_array($fieldElement, $valueArray)  === true
				OR ($this->_selectCounter== 0 AND $this->params->get('checkbox_first_selected',0)) )
			{
				$html .= 'checked ';
			}
			$html .= ' '.$this->attributes.' ';
			$html .= '/><label for="' . $this->getInputName() . '_' . $this->_selectCounter . '">'.JText::_($fieldElement).'</label>';
			$this->_selectCounter++;
			$html .= '</div>';
		}
		$html .= '</div>';
		return $html;
	}
	function getInputName($type=''){
		if($type=='cookie'){
			//echo parent::getInputName().'_'.$this->_selectCounter;
			return parent::getInputName().'_'.$this->_selectCounter;
		}else{
			return parent::getInputName()."[".($this->_selectCounter)."]";
		}
	}
	function getRecordedFieldId(){
		return '<input type="hidden" name="'.parent::getInputName().'_id" value="'.$this->field_id.'" />';
	}
	function getMySQLOutput(){
			return implode(', ',$this->uservalue);
	}
	function getSelectAllLink($classid){
		if($this->params->get('select_all_button', 0)){
			$doc	=& JFactory::getDocument();
			$buttonid	= 'check-all-'.$classid;
			$script = "
window.addEvent('domready', function() {
	$('".$buttonid."').addEvent('click', function() {
		var txtSelect_all	= '".JText::_('CHECKBOX_SELECT_ALL')."';
		var txtSelect_none	= '".JText::_('CHECKBOX_SELECT_NONE')."';
		$$('.check-me-".$classid."').each(function(el) { el.checked = $('".$buttonid."').checked; });
		if($('".$buttonid."').checked){
			$('labelcheckall-".$classid."').setText(txtSelect_none);
		}else{
			$('labelcheckall-".$classid."').setText(txtSelect_all	);
		}
	});
});";
			$doc->addScriptDeclaration($script);
			return '<div class="check-all"><input type="checkbox" class="cf-input-checkbox" name="'.$buttonid.'" id="'.$buttonid.'" /><label for="'.$buttonid.'" id="labelcheckall-'.$classid.'">'.JText::_('CHECKBOX_SELECT_ALL').'</label></div>';
		}
		return '';
	}
	
}

class ceFieldType_campaignmonitor extends ceFieldType{
	var $_selectCounter = 0;
	var $cm 			= null;
	var $apiKey			= null;
	var $clientID		= null;
	var $list			= null;
	
	function ceFieldType_campaignmonitor($data,&$params ) {
		parent::ceFieldType( $data,$params );
		
		require_once JPATH_ROOT.DS.'components'.DS.'com_contact_enhanced'.DS.'helper'.DS.'CMBase.php';
		
		if (is_string($this->params)) {
			$this->params = new JParameter($this->params);
		}
		$this->apiKey	= $this->params->get('campaignmonitor_api_key');
		$this->clientID	= $this->params->get('campaignmonitor_api_client');
		$this->list		= $this->params->get('campaignmonitorlist');
		
		$this->cm = new CampaignMonitor( $this->apiKey, $this->clientID );
		//Optional statement to include debugging information in the result
		$this->cm->debug_level = 1;
		
	}
	
	function getInputHTML() {
		$this->_selectCounter = 0;
		
		$html		= '<div class="cf-campaignmonitor">';
		
		if(!$this->clientID OR !$this->apiKey){
			$html	.= '<h1>'.JText::_('You must enter a valid API Key and a API Client ID').'</h1>'; 	
		}
		
		if($this->list){
			$listDetails	= $this->cm->listGetDetail($this->list);
			$html			.= $this->getOption($html,$listDetails,'ListID','Title');
			
		}else{
			$listTypes		= $this->cm->clientGetLists($this->clientID);
		//	testArray($listTypes);
			$this->getOption($html,$listTypes);
			/*foreach ($listTypes as $lists){
				foreach ($lists as $listDetails){
					if(is_array($listDetails)){
						foreach ($listDetails as $value) {
							$html	.= $this->getOption($html,$value);
						}
					}else{
						$html	.= $this->getOption($html,$listDetails);
					}
				}
			}*/
		}
			
		$html		.= '</div>';
		return $html;
	}
	
	/**
	 * Subscribes the user to the selected lists. Does not show an email output as the name sugests 
	 * @return	error message(s)
	 * 0: Success
	 * 1: Invalid email address
	 * The email value passed in was invalid.
	 * 100: Invalid API Key
	 * The API key pass was not valid or has expired.
	 * 101: Invalid ListID
	 * The ListID value passed in was not valid.
	 * 204: In Suppression List
	 * Address exists in suppression list. Subscriber is not added.
	 * 205: Is Deleted
	 * Email Address exists in deleted list. Subscriber is not added.
	 * 206: Is Unsubscribed
	 * Email Address exists in unsubscribed list. Subscriber is not added.
	 * 207: Is Bounced
	 * Email Address exists in bounced list. Subscriber is not added.
	 * 208: Is Unconfirmed
	 * Email Address exists in unconfirmed list. Subscriber is not added.
	 */
	function getEmailOutput() {
		$errors = array();
		$this->uservalue	= (array) $this->uservalue;
		if($this->clientID AND $this->apiKey AND count($this->uservalue) > 0){
			$name	= JRequest::getString( 'name', null,'post');
			$email	= JRequest::getString( 'email', null,'post');
			
			foreach ($this->uservalue as $list) {
				$errors[] = $this->cm->subscriberAdd($email,$name,$list);
			}
		}
		return $erros;
	}
	
	function getInputName($type=''){
		if($type=='cookie'){
			//echo parent::getInputName().'_'.$this->_selectCounter;
			return parent::getInputName().'_'.$this->_selectCounter;
		}else{
			return parent::getInputName()."[".($this->_selectCounter)."]";
		}
	}
	function getMySQLOutput(){
			return implode(', ',$this->uservalue);
	}
	function getOption(&$html,$list,$value_name='ListID', $text_name='Name') {
		//testArray($list);
		if(!isset($list[$value_name]) AND is_array($list)){
			foreach ($list as $value)
			$this->getOption($html,$value,$value_name,$text_name);
			//return	$this->getOption($html,$value,$value_name,$text_name);
		}elseif (is_array($list)){
			$cols	= $this->params->get('number_of_columns',1);
			$width	= number_format( (100/$cols), 1);
			$html .= '<div style="width:'.$width.'%;float:left">';
			$html .= '<input type="checkbox" class="cf-input-checkbox'.($this->isRequired() ? ' required validate-checkbox':'').'" '
						.' name="' . $this->getInputName(). '" '
						.' value="'.$list[$value_name].'" '
						.' id="' . $this->getInputName() . '_' . $this->_selectCounter . '" ';
			if( $list[$value_name] == $this->getValue() OR $this->params->get('cm-all-checked')){
				$html .= ' checked ';
			}
			$html .= ' '.$this->attributes.' ';
			$html .= '/><label for="' . $this->getInputName() . '_' . $this->_selectCounter . '">'.JText::_($list[$text_name]).'</label>';
			$html .= '</div>';
			$this->_selectCounter++;
		}
		
		//return $html;
	}
}

class ceFieldType_date extends ceFieldType {
	function getInputHTML() {
		$fieldAttributes	= ' class="inputbox'.($this->isRequired() ? ' required':'').'" '.$this->attributes;
		$html	= JHTML::_('calendar', $this->getValue(), $this->getInputName(), $this->getInputName(), JText::_('CF_DATE_FORMAT'), $fieldAttributes);
		return $html;
	}
}

class ceFieldType_daterange extends ceFieldType_date {
	var $_selectCounter	= 0;
	function getInputHTML() {
		$this->_selectCounter	= 0;
		$html	= parent::getInputHTML($this->_selectCounter);
		$html	.= ' '.JText::_('CF_DATE_RANGE_TO').' ';
		$this->_selectCounter	= 1;
		$html	.= parent::getInputHTML($this->_selectCounter);
		return $html;
	}
	function getInputName($type=''){
		if($type=='cookie'){
			//echo parent::getInputName().'_'.$this->_selectCounter;
			return parent::getInputName().'_'.$this->_selectCounter;
		}else{
			return parent::getInputName()."[".($this->_selectCounter)."]";
		}
	}
	function getRecordedFieldId(){
		return '<input type="hidden" name="'.parent::getInputName().'_id" value="'.$this->field_id.'" />';
	}
	function getEmailOutput($delimiter= ', ',$format='text',$style=array('label'=>'','value'=>'')){
		return parent::getEmailOutput(' '.JText::_('DATE_RANGE_TO').' ', $format, $style);
	}
}

class ceFieldType_multiplefiles extends ceFieldType {
	function getInputHTML() {

		$max_file_size	= (int) $this->params->get('max_file_size',300);
		$max_file_size	= $max_file_size * 1024;
		$number_of_files= (int) $this->params->get('mf_number_of_files',3);
		$doc	= & JFactory::getDocument();
		//$doc->addScript( JURI::root(). 'components/com_contact_enhanced/helper/multiupload/Stickman.MultiUpload.compressed.js' );
		$doc->addScript( JURI::root(). 'components/com_contact_enhanced/helper/multiupload/Stickman.MultiUpload.js' );
		$doc->addStyleSheet(	 JURI::root(). 'components/com_contact_enhanced/helper/multiupload/Stickman.MultiUpload.css');
		$script	= '<script type="text/javascript">'."window.addEvent('domready', function(){ "
		//. " new MultiUpload( $( 'emailForm' ).".$this->getInputName().", 3, '[{id}]', true, true );"
		. "var multipleUpload = new MultiUpload({
		deleteimg:	'".JURI::base()."components/com_contact_enhanced/helper/multiupload/cross_small.gif',
		input_element: $( 'emailForm' ).".$this->getInputName().",
		max:					'".$number_of_files."',
		name_suffix_template:	'[{id}]',
		show_filename_only:		true,
		required:				".($this->isRequired() ? 'true' : 'false').",
		remove_empty_element:	true,
		language: {
			txtdelete:			'".JText::_('Remove file')."',
			txtnotfileinput:	'".JText::_('Error: not a file input element')."',
			txtnomorethan:		'".JText::_('You may not upload more than')."',
			txtfiles:			'".JText::_('files')."',
			txtareyousure:		'".JText::_('Are you sure you want to remove the item')."',
			txtfromqueue:		'".JText::_('from the upload queue?')."'
			}
  	});"
  	. " });</script>";

  	JApplication::addCustomHeadTag($script);
  	$html	= '<input type="file" class="cf-input-file" name="'.$this->getInputName().'" id="'.$this->getInputName().'" '.$this->attributes
  	. ' class="inputbox '.(($this->isRequired() AND $this->published) ? ' required':'').'" '
  	.' />'
  	.'<input type="hidden" name="MAX_FILE_SIZE" value="'.$max_file_size.'" /><br clear="all" />';
  	$html	.= '<small>'. JText::_('Max file size allowed').': '.ceHelper::formatBytes($max_file_size).'</small>';
  	return $html;
	}
	
	function validateFileExtension(&$filename){
		$filter_file_extensions	= $this->params->get('mf_filter_file_extensions');
		$mf_filter_type			= $this->params->get('mf_filter_type');
		$file_extension			= JFile::getExt($filename);

		if($mf_filter_type == 'blacklist' AND stripos($filter_file_extensions,$file_extension) === true){
			$this->errors[]	= JText::_('File type not allowed');
			return false;
		}else if($mf_filter_type == 'whitelist' AND stripos($filter_file_extensions,$file_extension) === false){
			$this->errors[]	=  JText::_('File type not allowed');
			return false;
		}
		return true;
	}
}

class ceFieldType_file extends ceFieldType {
	function getInputHTML() {
		$html	= '<input type="file" class="cf-input-file" name="'.$this->getInputName().'" id="'.$this->getInputName().'" '.$this->attributes
		. ' class="inputbox '.(($this->isRequired() AND $this->published) ? ' required validate-file':'').'" '
		.' />'
		.'<input type="hidden" name="MAX_FILE_SIZE" value="102400" /><br/>';
		return $html;
	}
}

class ceFieldType_name extends ceFieldType {
	function getInputHTML() {
		$user		= &JFactory::getUser();
		$html	= '<input type="'.($this->published ? 'text' : 'hidden').'" name="name" id="name" '
				//. ($user->get('name') ? ' readonly ' : '')
				. ' class="inputbox cf-input-text'.(($this->isRequired() AND $this->published) ? ' required':'').'" '
				. ' value="'. ($this->getValue() ? $this->getValue() : $user->get('name') ). '" '.$this->attributes.' />';
		return $html;
	}
	function getInputName(){
		return 'name';
	}
}
class ceFieldType_surname extends ceFieldType {
	function getInputName(){
		return 'cf_surname';
	}
}
class ceFieldType_email extends ceFieldType {
	function getInputHTML() {
		if(!$this->params->get('plugin_active') AND $this->getValue() ){
			$value	= $this->getValue();
		}elseif(!$this->params->get('plugin_active')){
			$user		= &JFactory::getUser();
			$value	= $user->get('email');
		}else{
			$value	= '';
		}
		
		$html	= '<input type="'.($this->published ? 'text' : 'hidden').'" id="email" name="email" '
					//. ($user->get('email') ? ' readonly ' : '')
					. ' class="inputbox cf-input-text'.(($this->isRequired() AND $this->published) ? ' required validate-email':'').'" '
					. ' value="'.$value. '" '.$this->attributes.' />';
		return $html;
	}
	function getInputName(){
		return 'email';
	}
}

class ceFieldType_subject extends ceFieldType {
	function getInputHTML() {
		if(count($this->arrayFieldElements) > 1){
			$html = '<select name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"'
					.	' class="inputbox text_area'.($this->isRequired() ? ' required':'').'" '.$this->attributes.' >';
			$html .= '<option value="">'.JText::_($this->params->get('first_option', 'Please select one')).'</option>';
			foreach($this->arrayFieldElements AS $fieldElement) {
				if(strpos($fieldElement, '::') > 0){
					$fieldElement = explode('::', $fieldElement);
				}else{
					$fieldElement = array($fieldElement,$fieldElement);
				}
				$html .= '<option value="'.JText::_($fieldElement[0]).'"';
				if( $fieldElement[0] == $this->getValue() ) {
					$html .= ' selected';
				}
				$html .= '>' . JText::_($fieldElement[1]) . '</option>';
			}
			$html .= '</select>'; 
		}else{
			$html	= '<input type="'.($this->published ? 'text' : 'hidden').'" name="subject" id="subject" '
				. ' class="inputbox cf-input-text'.(($this->isRequired() AND $this->published) ? ' required':'').'" '
				. ' value="'. ($this->getValue() ? $this->getValue() : '' ). '" '.$this->attributes.' />';
		}
		return $html;
	}
	function getInputName(){
		return 'subject';
	}
	function getValue($arg=null){
		if($this->value){
			return $this->value;
		}else{
			$ce_cookie		= JRequest::getVar( 'ce_cookie',	'',	'cookie' );
			if( isset($ce_cookie[$this->getInputName('cookie')]) ){
				return $ce_cookie[$this->getInputName('cookie')];
			}
		}
	}
}
class ceFieldType_numberrange extends ceFieldType{
	var $_selectCounter = 0;
	function getInputHTML() {
		$html = '';
		$this->_selectCounter = 0;
		foreach($this->arrayFieldElements AS $fieldElements) {
			$fieldElement = explode('-',$fieldElements);
				
			if(count($this->arrayFieldElements) == 1){
				$nrLabel = JText::_('Please select one');
			}elseif($this->_selectCounter > 0){
				$nrLabel = JText::_('NUMBER_RANGE_TO');
			}else{
				$nrLabel = JText::_('NUMBER_RANGE_FROM');
			}
				
				
			$html .= '<select name="' . $this->getInputName() . '" id="' . $this->getInputName() . '" class="inputbox text_area'.($this->isRequired() ? ' required':'').'" '.$this->attributes.' >';
			$html .= '<option value="">'.$nrLabel.'</option>';
			for($i=$fieldElement[0]; $i <= $fieldElement[1]; $i++){
				$html .= 	'<option value="'.$i.'"';
				if( $i == $this->getValue() ) {
					$html .= ' selected';
				}
				$html .=	' >'.$i.'</option>';
			}
			$html .= '</select> ';
			$this->_selectCounter++;
		}
		return $html;
	}
	function getInputName($type=''){
		if($type=='cookie'){
			//echo parent::getInputName().'_'.$this->_selectCounter;
			return parent::getInputName().'_'.$this->_selectCounter;
		}else{
			return parent::getInputName()."[".($this->_selectCounter)."]";
		}
	}
	function getRecordedFieldId(){
		return '<input type="hidden" name="'.parent::getInputName().'_id" value="'.$this->field_id.'" />';
	}

	function getEmailOutput($delimiter= ', ',$format='text',$style=array('label'=>'','value'=>'')){
		return parent::getEmailOutput(' '.JText::_('NUMBER_RANGE_TO').' ', $format, $style);
	}
}
class ceFieldType_number extends ceFieldType_numberrange{
	
}

class ceFieldType_freetext extends ceFieldType {
	function getInputHTML() {
		return '<div class="ce-freetext-container" '.$this->attributes.' >'.JText::_($this->getValue()).'</div>';
	}
	function getValue(){
		if($this->params->get('parse_content_plugins',0)){
			/*
			 * Handle display events
			 */
			
			$dispatcher	=& JDispatcher::getInstance();
			// add full article object to avoid problems with plugins
			$article = new stdClass();
			$article->id	= 0;
			$article->catid	= 0;
			$article->title			= '';
		    $article->alias			= '';
		    $article->title_alias	= '';
		    $article->introtext		= '';
		    $article->fulltext		= '';
		    $article->state			= 1;
		    $article->sectionid		= 0;
		    $article->mask			= '';
		    $article->created		= 0;
		    $article->created_by	= 0;
		    $article->created_by_alias	= 0;
		    $article->modified		= 0;
		    $article->modified_by	= 0;
		    $article->checked_out	= 0;
		    $article->checked_out_time	= 0;
		    $article->publish_up	= 0;
		    $article->publish_down	= 0;
		    $article->images		= '';
		    $article->urls			= '';
		    $article->attribs		='';
			$article->text	= parent::getValue();
			$article->event = new stdClass();
			
			/*
			 * Process the prepare content plugins
			 */
			JPluginHelper::importPlugin('content');
						
			$results = $dispatcher->trigger('onPrepareContent', array ($article, &$this->params, 0));
			$article->event->onPrepareContent	= trim(implode("\n", $results));
			
			$results = $dispatcher->trigger('onAfterDisplayTitle', array ($article, &$this->params, 0));
			$article->event->afterDisplayTitle	= trim(implode("\n", $results));
	
			$results = $dispatcher->trigger('onBeforeDisplayContent', array (& $article, & $this->params, 0));
			$article->event->beforeDisplayContent	= trim(implode("\n", $results));
	
			$results = $dispatcher->trigger('onAfterDisplayContent', array (& $article, & $this->params, 0));
			$article->event->afterDisplayContent	= trim(implode("\n", $results));
			

			return $article->text;
		}else{
			return parent::getValue();
		}
	}
}

class ceFieldType_password extends ceFieldType {
	function getInputHTML() {
		$fieldAttributes	= ' class="inputbox'.($this->isRequired() ? ' required':'').'" '.$this->attributes;
		$html	= '<input type="password" class="cf-input-text cf-input-password" name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"  '.$fieldAttributes.' />';
		return $html;
	}
}

class ceFieldType_username extends ceFieldType {
	function getInputHTML() {
		$doc =& JFactory::getDocument();
		$logDiv	= 'CElog_res';
	$script = "
window.addEvent('domready', function(){
	$('ce-username').addEvent('blur', function(e) {
		//e = new Event(e).stop();
		var url	= '".JURI::root()."index.php?option=com_contact_enhanced&task=checkusername&tmpl=raw';
		var log_res = '".$logDiv."';
		//build the request
		var jSonRequest = new Json.Remote(url, {onComplete: function(response){
				//did it return as good, or bad?
				if(response.action == 'success'){
					//username is available
					$('ce-username').removeClass('invalid');
					$('ce-username').addClass('success');
					
					//update the response p
					$(log_res).removeClass('ajax-loading');
					$(log_res).setHTML('<em>'+response.username+'</em> ".JText::_('USERNAME IS AVAILABLE')."');
					$(log_res).setStyle('display','block');
					
				}else{
					//username is taken
					$('ce-username').removeClass('success');
					$('ce-username').addClass('invalid');
					
					//update the response p
					$(log_res).removeClass('ajax-loading');
					$(log_res).setHTML('<em>'+response.username+'</em> ".JText::_('USERNAME IS NOT AVAILABLE')."');
					$(log_res).setStyle('display', 'block'); 
				}
				
			}
		}).send(Json.toString({'username':$('ce-username').value,'email':$('email').value})); 
	});
	
});
";
		$doc->addScriptDeclaration($script);
		$fieldAttributes	= ' class="inputbox'.($this->isRequired() ? ' required':'').'" '.$this->attributes;
		$html	= '<input type="text" name="username" class="cf-input-text cf-input-username" id="ce-username"  '.$fieldAttributes.' value="'.htmlspecialchars($this->getValue()).'" />';
		$html	.= '<div id="'.$logDiv.'" ></div>';
		return $html;
	}
	function getInputName(){
		return 'username';
	}	
}

class ceFieldType_hidden extends ceFieldType {
	function getInputHTML() {
		$html	= '<input type="hidden" name="' . $this->getInputName() . '" id="' . $this->getInputName() . '"  value="' . htmlspecialchars($this->getValue()) . '" '.$this->attributes.' />';
		return $html;
	}
}

class ceFieldType_sql extends ceFieldType {
	function getInputHTML() {
		JHTML::_('behavior.mootools');
		$doc	= & JFactory::getDocument();
		$doc->addScript( JURI::root(). 'components/com_contact_enhanced/assets/js/addtablerow.js' );
		$db		=& JFactory::getDBO();
		
		$javascript	= '';
		if($this->params->get('chain_select') AND $this->params->get('chain_select-enabled-option')){
			$javascript	= "onchange=\"JsonSelect.updateSelect('".$this->params->get('chain_select-enabled-option')."',this,'".JURI::root()."');\"";
			$doc->addScript(JURI::root().'components/com_contact_enhanced/assets/js/chainSelectList.js');
		}
		
		if($this->value){
			
			if($this->params->get('isAdmin')){
				//echo '<pre>'; print_r($this); exit;
				$query	= 'SELECT m.from_id FROM #__contact_enhanced_messages m '
							.	' INNER JOIN #__contact_enhanced_message_fields mf ON mf.message_id = m.id'
							.	' WHERE mf.id='.$db->Quote($this->field_id);
				$db->setQuery($query);
				$user	= $db->loadResult();
				$user	= &JFactory::getUser($user);
			}else{
				$user	= &JFactory::getUser();
			}
			
			
			$regex = '/{user_id}/i';
			$this->value  = preg_replace( $regex, $user->id, $this->value );
			
			$regex = '/{user_email}/i';
			$this->value  = preg_replace( $regex, $user->email, $this->value );
			
			$regex = '/{username}/i';
			$this->value  = preg_replace( $regex, $user->username, $this->value );
			
			$regex = '/{selectresult}/i';
			$isChainSelect  = preg_match( $regex, $this->value );
			
			$db->setQuery( $this->value );
			//echo '<pre>'.$db->getQuery( ).'</pre>'; exit;
			$rows = $db->loadObjectList();
		}
		if(count($rows) <= 0 AND !$this->params->get('hide_field') AND !$isChainSelect){
			return JText::_($this->params->get('sql_no_result_msg',''));
			
		}else if($this->params->get('hide_field') ){
			$html	= '';
			$i = 0;
			foreach($rows as $row){
				$html	.= '<input type="hidden" value="'.$row->value.'" name="'.$this->getInputName().'['.$i++.']" />';
			}
			return $html;
			
		}else if(count($rows) > 0 OR $isChainSelect){
			$options	= array();
			$options[]	= JHTML::_('select.option',  '', JText::_($this->params->get('first_option', 'Please select one')) );
			$fieldClass	= ' class="inputbox cf-input-text ce-cf-sql-quantity'.($this->isRequired() ? ' required':'').'" ';
			foreach($rows as $row){
				if( substr($row->text,0,2) == '--'){
					$options[]	=	JHTML::_('select.optgroup',  str_replace('--','',JText::_( $row->text ) ) );
				}else{
					$options[]	=	JHTML::_('select.option',  $row->value, JText::_( $row->text ) );
				}
			}

			if(isset($this->field_value)){
				$valueArray	= explode("\n", $this->field_value);
			}else{
				$valueArray	= array($this->getValue());				
			}
			
			
			$html	= '';
			$addButton	='<div>'
						.' <a href="#'.JText::_( 'CF_SQL_ADD' ).'" onclick="inject_row(\''.parent::getInputName().'\')">'.JText::_( 'CF_SQL_ADD_ITEM' ).'</a>'
						.' <a href="#'.JText::_( 'CF_SQL_REMOVE' ).'" onclick="remove_row(\''.parent::getInputName().'\')">'.JText::_( 'CF_SQL_REMOVE_ITEM' ).'</a>'
					.'</div>';
			
			
			$html	.= '<div id="'.parent::getInputName().'-container">';
				$html .= '<table id="'.parent::getInputName().'_table">'
						. '<tbody id="'.parent::getInputName().'_table_body">';
				if($this->params->get('sql_show_heading',1)){
					$html	.= '<tr>'
								.'<td class="sectiontableheader">'.JText::_($this->params->get('sql_item_label','CF_SQL_ITEM')).'</td>'
								//.'<th></th>'
								. ($this->params->get('sql_show_quantity',1) ? '<td class="sectiontableheader">'.JText::_($this->params->get('sql_quantity_label','CF_SQL_QUANTITY')).'</th>' : '')
							. '</tr>'
							;
				}
				for($i=1;$i<=count($valueArray);$i++){		
					$value	= explode('::', $valueArray[($i-1)]);

					$option	= JHTML::_('select.genericlist',   $options, $this->getInputName().'[value][]', $javascript.' size="1" '.$this->attributes.$fieldClass, 'value', 'text', trim($value[0]) );
					$html	.= '<tr id="'.parent::getInputName().'_tr['.$i.']" class="sectiontableentry1">'
								.'<td>'.$option.'</td>'
								//.'<td></td>'
								. ($this->params->get('sql_show_quantity',1) ? '<td>'
									.'<input type="text" name="'.$this->getInputName().'[quantity][]" '.$fieldClass
										. ($this->params->get('sql_quantity_validation') ? ' onkeydown="return '.$this->params->get('sql_quantity_validation').'(event);" ' : '' )
										. ' value="'.(isset($value[1]) ? trim($value[1]) : '').'" '
										.' /></td>' 
									: '')
							. '</tr>'
							;
				}
				$html	.= '</tbody>'
					. '</table> ';
			$html	.='</div>';
			if($this->params->get('sql_allow_multiple_lines',1)){
				$html	.= $addButton;
			}
			$html	.= '<input type="hidden" name="'.parent::getInputName().'_row_count" id="'.parent::getInputName().'_row_count" value="'.($i-1).'" />';
			return $html;
		}else if($isChainSelect > 0){ // 
			
		}
		
	}

	
	function getEmailOutput($delimiter= ', ',$format='text',$style=array('label'=>'','value'=>'')){
		$html	= '';
		if($format == 'html'){
			$html	.= '<div class="ce-cf-container">';
				$html .= '<span style="'.$style['label'].'">'.$this->getInputFieldName().'</span>' ;
				for($i=0; $i < count($this->uservalue['value']); $i++){
					$html	.= '<br /><span style="'.$style['value'].'"><strong>'.$this->uservalue['value'][$i].'</strong>'.( isset($this->uservalue['quantity'][$i]) ? ":: \t".$this->uservalue['quantity'][$i] : '').'</span>';
				}				
			$html	.= '</div>';
				
		}else{
			$html .= $this->getInputFieldName().": ";
			//if there is more than one value, add a break line between the label and values
			if(count($this->uservalue['value']) > 1){
				$html .= "\n ";
			}
			for($i=0; $i < count($this->uservalue['value']); $i++){
				$html	.= $this->uservalue['value'][$i].( isset($this->uservalue['quantity'][$i]) ? ":: \t".$this->uservalue['quantity'][$i] : '');
				$html	.= "\n";
			}
		}
		return $html;
	}
	
	function getMySQLOutput(){
		$html	= '';
		for($i=0; $i < count($this->uservalue['value']); $i++){
			$html	.= $this->uservalue['value'][$i].( isset($this->uservalue['quantity'][$i]) ? ":: \t".$this->uservalue['quantity'][$i] : '');
		}
		return $html;
	}
}

class ceFieldType_sqlmultiple extends ceFieldType {
	
	function getInputHTML() {
		JHTML::_('behavior.mootools');
		$doc	= & JFactory::getDocument();
		$doc->addScript( JURI::root(). 'components/com_contact_enhanced/assets/js/addtablerow.js' );
		
		
		$row	= array();
		
		if($this->value){
			$fields	= $this->getFields();
		}
		if(count($fields) < 1 AND !$this->params->get('hide_field') AND !$isChainSelect){
			return JText::_($this->params->get('sql_no_result_msg',''));
			
		}else if($this->params->get('hide_field') ){
			$html	= '';
			$i = 0;
			foreach($fields as $row){
				$html	.= '<input type="hidden" value="'.$row->value.'" name="'.$this->getInputName().'['.$i++.']" />';
			}
			return $html;
			
		}else if(count($fields) > 0 OR $isChainSelect){
			$html	= '';
			$addButton	='<div>'
						.' <a href="javascript:void(0);" onclick="inject_row(\''.parent::getInputName().'\')">'.JText::_( 'CF_SQL_ADD_ITEM' ).'</a>'
						.' <a href="javascript:void(0);" onclick="remove_row(\''.parent::getInputName().'\')">'.JText::_( 'CF_SQL_REMOVE_ITEM' ).'</a>'
					.'</div>';
			
			
			$html	.= '<div id="'.parent::getInputName().'-container">';
				$html .= '<table id="'.parent::getInputName().'_table">'
						. '<tbody id="'.parent::getInputName().'_table_body">';
				if($this->params->get('sql_show_heading',1)){
					$html	.= '<tr>';
						$html	.= $this->getFieldsHeading($fields);
					$html	.= '</tr>';
				}
				$html	.= $this->getFieldsHTML($fields);
				
				$html	.= '</tbody>'
					. '</table> ';
			$html	.='</div>';
			if($this->params->get('sql_allow_multiple_lines',1)){
				$html	.= $addButton;
			}
			return $html;
		}else if($isChainSelect > 0){ // 
			
		}
		
	}
	
	function getFieldsHeading(&$fields){
		$html	= '';
		foreach ($fields as $field) {
			$html	.= '<th class="sectiontableheader">'.$field[0].'</th>';
		}
		$html	.= ($this->params->get('sql_show_quantity',1) ? '<th class="sectiontableheader">'.JText::_($this->params->get('sql_quantity_label','CF_SQL_QUANTITY')).'</th>' : '');
		return $html;
	}
	
	function getFieldsHTML(&$fields) {
		
		$html	= '';
		$db		=& JFactory::getDBO();
		
		$javascript	= '';
		if($this->params->get('chain_select') AND $this->params->get('chain_select-enabled-option')){
			$javascript	= "onchange=\"JsonSelect.updateSelect('".$this->params->get('chain_select-enabled-option')."',this,'".JURI::root()."');\"";
			$doc->addScript(JURI::root().'components/com_contact_enhanced/assets/js/chainSelectList.js');
		}
		$value	= $this->getValue('session');
		
		if(isset($value[0])){
			$rowCount	= count($value[0]);
		}else{
			$rowCount	= 1;
		}
		$k=1;
		$html	.= '<input type="hidden" name="'.parent::getInputName().'_row_count" id="'.parent::getInputName().'_row_count" value="'.($rowCount).'" />';
		for($i=1;$i<=$rowCount;$i++){		
			$html	.= '<tr id="'.parent::getInputName().'_tr['.$i.']" class="sectiontableentry'.($k).'">';
			
			$fieldClass	= ' class="inputbox cf-input-select ce-cf-sqlmultiple'.($this->isRequired() ? ' required':'').'" ';
			
			for($j=0; $j < count($fields); $j++){
				$field	= $fields[$j][1];
				$option	= JHTML::_('select.genericlist',   $field, $this->getInputName().'['.$j.'][]', $javascript.' size="1" '.$this->attributes.$fieldClass, 'value', 'text', ( isset($value[$j][$i-1]) ? trim($value[$j][$i-1]) : '' ));
				$html	.=	'<td>'.$option.'</td>';
			}
			
			$fieldClass	= ' class="inputbox cf-input-text ce-cf-sql-quantity'.($this->isRequired() ? ' required':'').'" ';
			$html	.= ($this->params->get('sql_show_quantity',1) ? '<td>'
						.'<input type="text" name="'.$this->getInputName().'['.($j).'][]" '.$fieldClass
							. ($this->params->get('sql_quantity_validation') ? ' onkeydown="return '.$this->params->get('sql_quantity_validation').'(event);" ' : '' )
							. ' value="'.(isset($value[$j][$i-1]) ? trim($value[$j][$i-1]) : '').'" '
							.' /></td>' 
						: '')
					;
			
			$html	.= '</tr>';
			$k	= ($k == 2 ? $k =1 : ++$k);
		}
	
		return $html;
	}
	
	function getFieldOptions($rows) {
		
		if(count($rows) > 0){
			$options	= array();
			$options[]	= JHTML::_('select.option',  '', JText::_($this->params->get('first_option', 'Please select one')) );
			$fieldClass	= ' class="inputbox cf-input-text ce-cf-sql-quantity'.($this->isRequired() ? ' required':'').'" ';
			foreach($rows as $row){
				if( substr($row->text,0,2) == '--'){
					$options[]	=	JHTML::_('select.optgroup',  str_replace('--','',JText::_( $row->text ) ) );
				}else{
					$options[]	=	JHTML::_('select.option',  $row->value, JText::_( $row->text ) );
				}
			}
		}
	}
	
	function getFields() {
		$db		=& JFactory::getDBO();
		$user	= &JFactory::getUser();
		$fields	= array();
		//Cast to make sure it is an array
		$this->arrayFieldElements	= (array) $this->arrayFieldElements;
		
		foreach ($this->arrayFieldElements as $fieldElement) {
			$regex = '/{user_id}/i';
			$value  = preg_replace( $regex, $user->id, $fieldElement );
			
			$regex = '/{user_email}/i';
			$value  = preg_replace( $regex, $user->email, $fieldElement );
			
			$regex = '/{username}/i';
			$value  = preg_replace( $regex, $user->username, $fieldElement );
			
			$regex = '/{selectresult}/i';
			$isChainSelect  = preg_match( $regex, $fieldElement );
			
			if(strpos($fieldElement, '::') > 0){
				$fieldElement = explode('::', $fieldElement);
			}else{
				$fieldElement = array('CF_SQL_ITEM',$fieldElement);
			}
			
			$db->setQuery( $fieldElement[1] );
			//echo '<pre>'.$db->getQuery( ).'</pre>'; exit;
			$rows		= $db->loadObjectList();
			$fields[]	= array(JText::_($fieldElement[0]),$rows); 
		}
		return $fields;
	}

	
	function getEmailOutput($delimiter= ', ',$format='text',$style=array('label'=>'','value'=>'')){
		$html	= '';
		$k		= 1;
		if($format == 'html'){
			$html	.= '<div class="ce-cf-container">';
				$html .= '<span style="'.$style['label'].'">'.$this->getInputFieldName().'</span>' ;
				$html	.= '<div id="'.parent::getInputName().'-container">';
					$html .= '<table id="'.parent::getInputName().'_table" cellpadding="3" cellspacing="4">'
							. '<tbody id="'.parent::getInputName().'_table_body">';
					if($this->params->get('sql_show_heading',1)){
						if($this->value){
							$fields	= $this->getFields();
							$html	.= '<tr>';
								$html	.= $this->getFieldsHeading($fields);
							$html	.= '</tr>';
						}
						
					}
					for($i=0; $i < count($this->uservalue[0]); $i++){
						$html	.= '<tr id="'.parent::getInputName().'_tr['.$i.']" class="sectiontableentry'.($k).'">';
						for($j=0; $j < count($this->uservalue); $j++){
							$html	.=	'<td>'.$this->uservalue[$j][$i].'</td>';
						}
						$html	.= '</tr>';
						$k	= ($k == 2 ? $k =1 : ++$k);
					}				
					
					$html	.= '</tbody>'
						. '</table> ';
				$html	.='</div>';
				
			$html	.= '</div>';
			///echo $html; exit;
		}else{
			$html .= $this->getInputFieldName().": ";
			//if there is more than one value, add a break line between the label and values
			if(count($this->uservalue[0]) > 1){
				$html .= "\n ";
			}
			for($i=0; $i < count($this->uservalue[0]); $i++){
				$fields	= array();
				for($j=0; $j < count($this->uservalue); $j++){
					if(isset($this->uservalue[$j][$i])){
						$fields[]	= $this->uservalue[$j][$i];
					}else 
						echo "<br>this->uservalue[$j][$i]<br>";
				}
				
				$html	.= implode(" ::\t",$fields)."\n";
			}
		}
		return $html;
	}
	
	function getMySQLOutput(){
		$html	= '';
		for($i=0; $i < count($this->uservalue['value']); $i++){
			$html	.= $this->uservalue['value'][$i].( isset($this->uservalue['quantity'][$i]) ? ":: \t".$this->uservalue['quantity'][$i] : '');
		}
		return $html;
	}
	
	function getArrayElem(&$array, $key1=null, $key2=null) {
		if (isset($array[$key1][$key2])) {
			;
		}
	}
}
class ceFieldType_wysiwyg extends ceFieldType {
	function getInputHTML() {
		$this->editor = &JFactory::getEditor();
		// parameters : areaname, content, width, height, cols, rows
		$html = '<textarea name="' . $this->getInputName() . '" id="' . $this->getInputName() . '" 
					class="inputbox text_area'.($this->isRequired() ? ' required':'').'" 
					style="display:none" >' 
					. $this->getValue() . '</textarea>';
		$html .= $this->editor->display( $this->getInputName().'_editor' ,  $this->getValue(), '90%', '200', '75', '20', false ) ;
		return $html;
	}
	function getValidationScript() {
		$script	= "\n var ".$this->getInputName().'_editor_text = '.$this->editor->getContent( $this->getInputName().'_editor' );
		//$script	.= "\n alert(".$this->getInputName()."_editor_text);";
		$script	.= "\n".'$("'.$this->getInputName().'").setProperty("value",'.$this->getInputName().'_editor_text);';
		return $script;
	}
}
?>