<?php

/**
 * JustifiedGallery for Contao
 *
 * Copyright (c) 2016 Benjamin Roth
 *
 * @license LGPL-3.0+
 */

namespace eSM_justifiedGallery;


/**
 * Extends the core gallery class with justifiedGallery.
 */
class ContentGallery extends \Contao\ContentGallery
{
	public function generate()
	{

		if ($this->eSM_jg_enable)
		{
			// Overwrite gallery template
			$this->galleryTpl = 'gallery_justifiedGallery';

			// justifiedGallery unique selector
			$strJgClass = 'justifiedGallery_' . $this->id;

			$arrCssID = $this->cssID;
			$arrClass = array();
			if ($arrCssID[1])
			{
				$arrClass = explode(' ', $arrCssID[1]);
			}
			$arrClass[] = $strJgClass;
			$this->cssID = array($arrCssID[0], implode(' ', $arrClass));

			// justifiedGallery configuration
			$config = array
			(
				'selector'    => '> figure',
				'captions'    => ($this->eSM_jg_captions ? true : false),
				'fixedHeight' => ($this->eSM_jg_fixedHeight ? true : false),
				'waitThumbnailsLoad' => ($this->eSM_jg_waitLoaded ? true : false),
				'lastRow' => 'center'
			);

			if ($this->eSM_jg_height)
			{
				$config['rowHeight'] = intval($this->eSM_jg_height);
			}

			$this->eSM_jg_maxHeight = deserialize($this->eSM_jg_maxHeight);
			if (isset($this->eSM_jg_maxHeight['value']) && $this->eSM_jg_maxHeight['value'])
			{
				$config['maxRowHeight'] = $this->eSM_jg_maxHeight['value'].($this->eSM_jg_maxHeight['unit'] == '%' ? '%' : '');
			}

			if ($this->eSM_jg_margins)
			{
				$config['margins'] = intval($this->eSM_jg_margins);
			}

			// Inject scripts and css
			$GLOBALS['TL_JQUERY'][] = '<script src="/system/modules/eSM_justifiedGallery/assets/lib/justifiedGallery/' . $GLOBALS['TL_ASSETS']['JUSTIFIEDGALLERY'] . '/js/jquery.justifiedGallery.min.js"></script>';
			$GLOBALS['TL_JQUERY'][] = "<script>(function($) { $('.".$strJgClass."').justifiedGallery(".json_encode($config).");})(jQuery);</script>";
			$GLOBALS['TL_CSS'][] = '/system/modules/eSM_justifiedGallery/assets/lib/justifiedGallery/' . $GLOBALS['TL_ASSETS']['JUSTIFIEDGALLERY'] . '/css/justifiedGallery.min.css';
			$GLOBALS['TL_CSS'][] = '/system/modules/eSM_justifiedGallery/assets/css/justifiedGallery.ext.min.css';
		}

		return parent::generate();
	}

}