<?php defined('_JEXEC') or die();
/**
 * @version		1.1.1
 * @package		Read More, Basic
 * @copyright	2009 Rockford Solutions, Inc. All rights reserved.
 * @license		GNU/GPL
 */

jimport('joomla.application.component.controller');

/**
 * Base Controller
 *
 * @package		Read More, Basic
 */
class ReadmoreController extends JController {
	/**
	 * Display the view
	 */
	public function display() {
		$user = &JFactory::getUser();
		
		$component = JComponentHelper::getComponent('com_readmore');
		$params    = new JParameter($component->params);
		$getemail  = $params->get('requireemail');
	
		if ($user->guest && $getemail == 'yes') {
			$email = JRequest::getVar('email', null);
			
			if (is_null($email)) {
				$session = JSession::getInstance('none', array());
				$email = $session->get('email', null, 'visitor');
			} else {
				if (!$this->_submit($email)) {
					$email = null;
					JRequest::setVar('error', 'Invalid Email Address');
				}
			}
			
			JRequest::setVar('view', is_null($email) ? 'email' : 'readmore');
		} else {
			JRequest::setVar('view', 'readmore');
		}
		
		parent::display();
	}
	
	/**
	 * Store the submitted email address
	 *
	 * @access	string	Email address
	 * @return	bool	TRUE on success, FALSE on failure
	 */
	protected function _submit($email) {
		$regex = '/^\s*[\w\-\.]+\@([\w\-]+\.)+[0-9A-Za-z]{2,4}\s*$/';
		
		if (preg_match($regex, $email)) {
			$model = &$this->getModel('email');
			$model->store($email);
			
			$session = &JSession::getInstance('none', array());
			$email = $session->set('email', $email, 'visitor');
			
			return true;
		} else {
			return false;
		}
	}
}
