.
 *
 * PHP version 5
 * @copyright  cgo IT, 2013
 * @author     Carsten Götzinger (info@cgo-it.de)
 * @package    rateit
 * @license    GNU/LGPL
 * @filesource
 */
namespace cgoIT\rateit;
class RateItPage extends \Frontend {
	
	/**
	 * Initialize the controller
	 */
	public function __construct() {
		parent::__construct();
		$this->loadDataContainer('settings');
	}
	
	public function generatePage($objPage, $objLayout, $objPageType) {
		if ($objPage->addRating) {
			$actRecord = $this->Database->prepare("SELECT * FROM tl_rateit_items WHERE rkey=? and typ='page'")
										->execute($objPage->id)
										->fetchAssoc();
			
			if ($actRecord['active']) {
				$this->import('rateit\\RateItRating', 'RateItRating');
				$this->RateItRating->rkey = $objPage->id;
				$this->RateItRating->generate();
				
				$rating = $this->RateItRating->output();
				$rating .= $this->includeJs();
				$rating .= $this->includeCss();
				
				$objTemplate = $objPageType->Template;
				if ($objTemplate) {
					if ($objPage->rateit_position == 'after') {
						$objTemplate->main .= $rating;
					} else {
						$objTemplate->main = $rating.$objTemplate->main;
					}
				}
			}
		}
	}
	private function includeCss() {
		$included = false;
		$strHeadTags = '';
		if (is_array($GLOBALS['TL_CSS'])) {
			foreach ($GLOBALS['TL_CSS'] as $script) {
				if ($this->startsWith($script, 'system/modules/rateit/public/css/rateit') === true) {
					$included = true;
					break;
				}
			}
		}
	    if (!$included) {
	    	$strHeadTags = '';
	    	switch ($GLOBALS['TL_CONFIG']['rating_type']) {
	    		case 'hearts' :
	    			$strHeadTags .= '';
	    			break;
	    		default:
	    			$strHeadTags .= '';
	    	}
	    }
		return $strHeadTags;
	}
	
	private function includeJs() {
		$included = false;
		$strHeadTags = '';
		if (is_array($GLOBALS['TL_JAVASCRIPT'])) {
			foreach ($GLOBALS['TL_JAVASCRIPT'] as $script) {
				if ($this->startsWith($script, 'system/modules/rateit/public/js/rateit') === true) {
					$included = true;
					break;
				}
			}
		}
	    if (!$included) {
	   		$strHeadTags = '' . "\n";
	   		$strHeadTags .= '' . "\n";
	    }
	   	return $strHeadTags;
	}
	
	function startsWith($haystack, $needle) {
	    // search backwards starting from haystack length characters from the end
	    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
	}
}
?>