<?php
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

defined('_JEXEC') or die;

require_once JPATH_ADMINISTRATOR . '/components/com_arismartcontent/kernel/class.AriKernel.php';

AriKernel::import('Parameters.ParametersHelper');
AriKernel::import('Application.ARISmartContent.Utils.Widget');
AriKernel::import('Application.ARISmartContent.Utils.ApplicationHelper');
AriKernel::import('Application.ARISmartContent.Providers.ProvidersHelper');
AriKernel::import('Web.JSON.JSON');
AriKernel::import('Document.DocumentHelper');
AriKernel::import('Web.HtmlHelper');
AriKernel::import('SimpleTemplate.SimpleTemplate');

jimport('joomla.filter.filterinput');

class AriSmartContentWidgetEasyslider extends AriSmartContentWidget
{
	var $_params;
	var $_id;

	function __construct($id, $params)
	{
		$this->_id = $id;
		$this->_params = AriParametersHelper::flatParametersToArray($params);
		
		$lang = JFactory::getLanguage();
		$lang->load('lib_arismartcontent_easyslider', JPATH_SITE);
	}

	function getId()
	{
		return $this->_id;
	}

	function loadAssets()
	{
		$appHelper = AriSmartContentApplicationHelper::getInstance();
		$appHelper->loadJQuery();
		$appHelper->loadJQueryLib('easing');

		$baseUri = JURI::root(true) . '/media/arismartcontent/easyslider/';

		AriDocumentHelper::includeJsFile($baseUri . 'js/jquery.easyslider.js');
	}

	function registerClientInstance()
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		$theme = AriUtils::getParam($mainParams, 'theme');

		$this->includeThemeAssets($theme);
		$loadMethod = AriUtils::getParam($mainParams, 'loadMethod', 'ready');

		$id = $this->getId();
		$jsOptions = $this->getJsOptions();

		$initCode = sprintf('$("#%1$s").easySliderPro(%2$s);',		
			$id,
			!empty($jsOptions) ? json_encode($jsOptions) : ''
		);

		$doc = JFactory::getDocument();
		if ($loadMethod == 'load')
			$doc->addScriptDeclaration(';(window["ascJQuery"] || jQuery)(window).load(function() { var $ = window["ascJQuery"] || jQuery;' . $initCode . '});');
		else
			$doc->addScriptDeclaration(';(window["ascJQuery"] || jQuery)(document).ready(function($) { ' . $initCode . '});');
			
		$width = intval(AriUtils::getParam($mainParams, 'width', 300), 10);
		$height = intval(AriUtils::getParam($mainParams, 'height', 300), 10);
		$itemsPerPage = AriUtils::getParam($jsOptions, 'itemsPerPage', 1);
		$vertical = AriUtils::getParam($jsOptions, 'vertical', false);
		$responsive = (bool)AriUtils::getParam($jsOptions, 'responsive', false);
		$itemWidth = $vertical ? $width : floor($width / $itemsPerPage);
		$itemHeight = $vertical ? floor($height / $itemsPerPage) : $height;

		$cssStyles = '';
		if ($width > 0 || $height > 0)
		{
			$cssStyles .= sprintf('#%1$s LI.es-news-item {%2$s%3$s}',
				$id,
				$width > 0 ? 'width:' . $itemWidth . 'px;' : '',
				$height > 0 ? 'height:' . $itemHeight . 'px;' : '');

			if ($width > 0)
				if ($responsive)
					$cssStyles .= sprintf('#%1$s_overlay {max-width:%2$dpx} ',
						$id,
						$width);
				else
					$cssStyles .= sprintf('#%1$s_overlay {width:%2$dpx} ',
						$id,
						$width);

			if ($height > 0)
				$cssStyles .= sprintf('#%1$s {height:%2$dpx}',
					$id,
					$height);
		}

		$customStyles = AriUtils::getParam($mainParams, 'customstyles');
		if ($customStyles)
			$cssStyles .= AriSimpleTemplate::parse($customStyles, array('id' => $id));

		if ($cssStyles)
			$doc->addStyleDeclaration($cssStyles);

		$this->_includeCustomStyles();
	}
	
	function includeThemeAssets($theme)
	{
		static $themes = array();

		if (empty($theme))
			$theme = 'default';

		$theme = JFilterInput::getInstance()->clean($theme, 'WORD');

		if (in_array($theme, $themes))
			return ;

		$themeUri = JURI::root(true) . '/media/arismartcontent/easyslider/themes/' . $theme . '/';
		AriDocumentHelper::includeCssFile($themeUri . 'styles.css');

		$themePath = JPATH_ROOT . '/media/arismartcontent/easyslider/themes/' . $theme . '/';
		if (@file_exists($themePath . 'styles.ie6.css'))
			AriDocumentHelper::includeCustomHeadTag(sprintf('<!--[if lt IE 7]><link rel="stylesheet" href="%s" type="text/css" /><![endif]-->',
				$themeUri . 'styles.ie6.css'));

		$themes[] = $theme;
	}
	
	function _includeCustomStyles()
	{
		$id = $this->getId();
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		
		$cssStyles = AriUtils::getParam($params, 'styles');
		$zIndex = intval(AriUtils::getParam($mainParams, 'zIndex'), 10);
		$style = '';

		$baseUri = JURI::root(true) . '/modules/mod_arieasyslider/includes/js/';
		$mapping = array('container' => '#' . $id, 'itemin' => '#' . $id . ' .es-news-item-in');
		$pxStyles = array('border-width', 'border-radius', 'padding');
		foreach ($mapping as $key => $cssSelector)
		{
			if (empty($cssStyles[$key]))
				continue ;

			$style .= ' ' . $cssSelector . '{';
			foreach ($cssStyles[$key] as $cssProp => $cssValue)
			{
				if (in_array($cssProp, $pxStyles) && $cssValue)
					$cssValue .= 'px';

				$style .= $cssProp . ':' . $cssValue . ';';
				if ($cssProp == 'border-radius')
				{
					$style .= sprintf('-moz-border-radius:%1$s;-webkit-border-radius:%1$s;', $cssValue);
				}
			}
			$style .= '}';
		}
		
		if ($zIndex > -1)
			$style .= sprintf(' #%1$s, #%1$s ul.es-items-container {z-index:%2$d}',
				$id,
				$zIndex); 

		if ($style)
		{
			$doc = JFactory::getDocument();
			$doc->addStyleDeclaration($style);
		}
	}

	function getJsOptions()
	{
		$params = $this->_params;
		$options = AriUtils::getParam($params, 'opt');

		$defOptions = array(
			'controlsShow' => true,
			'controlsFade' => true,
			'vertical' => false,
			'speed' => 800,
			'auto' => false,
			'pause' => 2000,
			'continuous' => false,
			'opposite' => false,
			'moveFx' => 'easeInOutBack',
			'pauseOnHover' => false,
			'opacity' => 1.0,
			'itemsPerPage' => 1,
			'startSlide' => 0,
			'oppositeMove' => false,
			'responsive' => false
		);

		$jsOptions = AriParametersHelper::getUniqueOverrideParameters($defOptions, $options);
		
		return $jsOptions;
	}

	function getItems($data)
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		
		$itemTemplate = AriUtils::getParam($mainParams, 'itemTemplate');

		$items = array();

        if (!empty($data))
        {
            foreach ($data as $dataItem)
            {
                $content = AriSimpleTemplate::parse($itemTemplate, $dataItem);

                $item = array(
                    'content' => $content
                );

                $items[] = $item;
            }
        }

		return $items;
	}

	function getTheme()
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		$theme = AriUtils::getParam($mainParams, 'theme');
		$appHelper = AriSmartContentApplicationHelper::getInstance();

		return $appHelper->resolveJQueryUITheme($theme);
	}
	
	function render()
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');

		$source = AriUtils::getParam($mainParams, 'source');
		$sourceData = AriSmartContentProvidersHelper::resolveSource($source);
		$data = AriSmartContentProvidersHelper::getData($sourceData, null);

		$items = $this->getItems($data);

		$this->renderItems($items);
	}

	function renderItems($items)
	{
		$this->loadAssets();
		$this->registerClientInstance();

		$this->renderTemplate($items);		
	}
	
	private function renderTemplate($items)
	{
		$params = $this->_params;
		$sliderId = $this->getId();

		require dirname(__FILE__) . '/tmpl/slider.php';
	}
}