<?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';
require_once JPATH_ADMINISTRATOR . '/components/com_arismartcontent/defines.php';

AriKernel::import('Parameters.ParametersHelper');
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');

class AriSmartContentWidgetCloudCarousel
{
	var $_params;
	var $_id;

	function __construct($id, $params)
	{
		$this->_id = $id;
		$this->_params = AriParametersHelper::flatParametersToArray($params);
	}

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

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

		$baseUri = JURI::root(true) . '/media/arismartcontent/cloudcarousel/';
		$jsUri = $baseUri . 'js/';
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');

		AriDocumentHelper::includeJsFile($jsUri . 'jquery.cloud-carousel.min.js');
		AriDocumentHelper::includeJsFile($jsUri . 'init.js');

		$theme = AriUtils::getParam($mainParams, 'theme');
		$filter = JFilterInput::getInstance();
		$theme = $filter->clean($theme, 'WORD');
		if (empty($theme)) 
			$theme = 'default';

		$doc = JFactory::getDocument();
		
		$doc->addStyleSheet($baseUri . 'themes/' . $theme . '/style.css');
	}

	function registerClientInstance()
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		$widgetParams = AriUtils::getParam($params, 'opt');
		$lightboxParams = AriUtils::getParam($params, 'lightbox');
		$appHelper = AriSmartContentApplicationHelper::getInstance();

		$loadMethod = AriUtils::getParam($mainParams, 'loadMethod', 'ready');

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

		$initCode =
			sprintf('cloudCarouselInit($, "#%1$s", $.extend(%2$s, {"buttonLeft": $("#%1$s_wrapper .ari-cloud-carousel-left"), "buttonRight": $("#%1$s_wrapper .ari-cloud-carousel-right"), "titleBox": $("#%1$s_wrapper .ari-cloud-carousel-title"), "altBox": $("#%1$s_wrapper .ari-cloud-carousel-alt")}),%3$s);%4$s',
				$id,
				!empty($jsOptions) ? json_encode($jsOptions) : '{}',
				(bool)AriUtils::getParam($mainParams, 'openOnlyActive', false) ? 'true' : 'false',
				$lightboxEngine ? $lightboxEngine->getInitClientCode('#' . $id, null) . ';' : ''
			);

		$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 . '});');

		$responsive = (bool)AriUtils::getParam($widgetParams, 'responsive', true);

		$width = intval(AriUtils::getParam($mainParams, 'width', 600), 10);
		$height = intval(AriUtils::getParam($mainParams, 'height', 450), 10);

		$styleDec = '';
		if (!$responsive)
			$styleDec .= sprintf('#%1$s_wrapper{width:%2$dpx;height:%3$dpx;}',
				$id,
				$width,
				$height);
		else 
			$styleDec .= sprintf('#%1$s_wrapper{max-width:%2$dpx;}',
				$id,
				$width
			);

		$styleDec .= sprintf('#%1$s{width:%2$dpx;height:%3$dpx;}',
			$id,
			$width,
			$height
		);
		
		$bgImage = AriUtils::getParam($mainParams, 'bgImage');
		if ($bgImage)
			$styleDec .= sprintf('#%1$s_wrapper{background:transparent url(%2$s) no-repeat center center;}',
				$id,
				AriUtils::isRemoteResource($bgImage) ? $bgImage : JURI::root(true) . '/' . $bgImage);

		$customStyles = trim(AriUtils::getParam($mainParams, 'customstyle', ''));
		if ($customStyles)
		{
			$customStyles = str_replace('{$id}', $id, $customStyles);
			if (!empty($customStyles))
				$styleDec .= $customStyles;
		}
		
		$doc->addStyleDeclaration($styleDec); 
	}

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

		$defOptions = array(
			'minScale' => 0.5,
			'reflHeight' => 0,
			'reflGap' => 0,
			'reflOpacity' => 0.0,
			'xRadius' => 0.0,
			'yRadius' => 0.0,
			'xPos' => 0,
			'yPos' => 0,
			'FPS' => 30,
			'speed' => 0.2,
			'autoRotate' => 'no',
			'autoRotateDelay' => 1500,
			'mouseWheel' => false,
			'reverseMouseWheel' => false,
			'bringToFront' => false,
			'keyboardNav' => false,
			'reverseKeyboardNav' => false,
			'startIndex' => 0,
			'onlyFrontDescription' => false,
			'disableTimer' => true,
			'stopInBackground' => false,
			'responsive' => true
		);

		$jsOptions = AriParametersHelper::getUniqueOverrideParameters($defOptions, $options);
		
		$width = intval(AriUtils::getParam($mainParams, 'width', 600), 10);
		$height = intval(AriUtils::getParam($mainParams, 'height', 450), 10);
		
		$jsOptions['width'] = $width;
		$jsOptions['height'] = $height;
		
		if (empty($jsOptions['xPos']))
			$jsOptions['xPos'] = (int)($width / 2);
		
		if (empty($jsOptions['yPos']))
			$jsOptions['yPos'] = (int)($height / 3);

		if (empty($jsOptions['xRadius']))
			$jsOptions['xRadius'] = (int)($width / 2.3);

		if (empty($jsOptions['yRadius']))
			$jsOptions['yRadius'] = (int)($height / 6);

		return $jsOptions;
	}

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

		$slides = array();
		$images = array();

		$useThumbs = (bool)AriUtils::getParam($mainParams, 'useThumbs');
		$defaultDescr = AriUtils::getParam($mainParams, 'defaultDescription');
		$defLink = AriUtils::getParam($mainParams, 'defaultLink');
		$processDefaultDescr = $defaultDescr && strpos($defaultDescr, '{$') !== false;
		foreach ($data as $dataItem)
		{
			$normalizedItem = AriParametersHelper::flatParametersToArray($dataItem);
			$item = AriUtils::getParam($normalizedItem, 'Item');

			if (empty($item) || empty($item['Url']))
				continue ;

			$itemParams = AriUtils::getParam($normalizedItem, '_default');
			$slide = array();//$itemParams;
			$image = $slide['image'] = $item['Url'];
			
			if (!empty($dataItem['Link']))
				$slide['link'] = $dataItem['Link'];
			else if (!empty($defLink))
				$slide['link'] = $defLink;

			if (!empty($itemParams['Title']))
				$slide['title'] = $itemParams['Title'];

			if (!empty($itemParams['Description']))
				$slide['description'] = $itemParams['Description'];
			else if ($defaultDescr)
				$slide['description'] = $processDefaultDescr
					? str_replace(
						array(
							'{$fileName}', 
							'{$baseFileName}'
						), 
						array(
							basename($image), 
							JFile::stripExt(basename($image))
						), 
						$defaultDescr
					  )
					: $defaultDescr;

			$thumbExist = false;
			if ($useThumbs)
			{
				$preview = AriUtils::getParam($normalizedItem, 'Preview');
				if (!empty($preview['Url']))
				{
					$thumbExist = true;
					if (empty($slide['link']))
						$slide['link'] = $slide['image'];
					$slide['image'] = $preview['Url'];
					
					if (!empty($preview['Width']))
						$slide['width'] = $preview['Width'];

					if (!empty($preview['Height']))
						$slide['height'] = $preview['Height'];
				}
			}

			if (!$thumbExist) 
			{
				if (!empty($item['Width']))
					$slide['width'] = $item['Width'];

				if (!empty($item['Height']))
					$slide['height'] = $item['Height'];		
			}

			$slides[] = $slide;
		}

		return $slides;
	}

	function prepareSlides($slides)
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		$lightboxParams = AriUtils::getParam($params, 'lightbox');
		$newSlides = array();

		$target = AriUtils::getParam($mainParams, 'customLinkTarget');
		if (empty($target))
			$target = AriUtils::getParam($mainParams, 'linkTarget', '_self');

		$defLink = AriUtils::getParam($mainParams, 'defaultLink');
		
		$lightboxEngine = null;

		$lightboxEngine = $this->getLightboxPlugin($lightboxParams);
		$lightboxGrouping = (bool)AriUtils::getParam($lightboxParams, 'grouping', true);
		$lightboxGroup = $lightboxGrouping ? uniqid('cc_') : null;

		foreach ($slides as $slide)
		{
			$defSlideLink = str_replace('{$originalImage}', $slide['image'], $defLink);
			
			$slideLink = !empty($slide['link']) ? $slide['link'] : $defSlideLink;
			if (empty($slide['link']) && !empty($defSlideLink))
				$slide['link'] = $defSlideLink;
			
			$isLink = !empty($slideLink);
			$description = isset($slide['description']) ? $slide['description'] : '';
			$title = isset($slide['title']) ? $slide['title'] : '';
		
			$lnkAttrs = null;
			$imgAttrs = array(
				'src' => $slide['image'], 
				'alt' => $description, 
				'title' => $title, 
				'class' => 'cloudcarousel'
			);

			if (!empty($slide['width'])) 
				$imgAttrs['width'] = $slide['width'];

			if (!empty($slide['height'])) 
				$imgAttrs['height'] = $slide['height'];

			if ($isLink)
			{
				$lnkAttrs = array(
					'href' => $slideLink, 
					'target' => $target
				);

				if ($description)
					$lnkAttrs['title'] = $description;

				$skip_lb = false;
				if (!is_null($lightboxEngine) && strpos($slideLink, 'skip_lb') !== false)
				{
					$uri = new JURI($slideLink);
					$skip_lb = (bool)$uri->getVar('skip_lb');
					$uri->delVar('skip_lb');
					$slideLink = $uri->toString();
					$lnkAttrs['href'] = $slideLink;
				}

				if (!$skip_lb && !is_null($lightboxEngine))
				{
					$lightboxEngine->processLink($lnkAttrs, $lightboxGroup, $lightboxParams);
				}
				else
				{
					$originalLink = $slideLink;
					if (strpos($originalLink, '_target') !== false)
					{
						$uri = new JURI($originalLink);
						$linkTarget = $uri->getVar('_target');
						if (!is_null($linkTarget))
						{
							$uri->delVar('_target');
							$lnkAttrs['target'] = $linkTarget;
							$lnkAttrs['href'] = $uri->toString();
						}
					}
				}
			}

			$slide['lnkAttrs'] = $lnkAttrs;
			$slide['imgAttrs'] = $imgAttrs;
			$newSlides[] = $slide;
		}

		return $newSlides;
	}

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

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

		$this->loadAssets();
		$this->registerClientInstance();

		$slides = $this->getSlides($data);
		$slides = $this->prepareSlides($slides);

		$this->renderTemplate($slides);
	}
	
	private function renderTemplate($slides)
	{
		$params = $this->_params;
		$carouselId = $this->getId();
		
		require dirname(__FILE__) . '/tmpl/carousel.php';
	}
	
	private function getLightboxPlugin($params)
	{
		$plg = null;

		$plgName = AriUtils::getParam($params, 'type');
		if (empty($plgName))
			return $plg;

		$helper = AriSmartContentApplicationHelper::getInstance();
		$plg = $helper->getPlugin(ARISMARTCONTENT_INTEGRATIONPLUGIN_TYPE, $plgName);

		if ($plg)
			$plg->loadAssets();

		return $plg;
	}
}