<?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') && defined('ARI_FRAMEWORK_LOADED')) or die;

require_once JPATH_ADMINISTRATOR . '/components/com_arismartcontent/kernel/class.AriKernel.php';
require_once dirname(__FILE__) . '/helper.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');

class AriSmartContentWidgetMediaGalleryBase
{
	var $_params;
	var $_id;

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

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

	function loadAssets()
	{
		static $loaded;

		if ($loaded)
			return ;
		
		$appHelper = AriSmartContentApplicationHelper::getInstance();
		$appHelper->loadJQuery();

		$baseUri = JURI::root(true) . '/media/arismartcontent/mediagallery/';
		$jsUri = $baseUri . 'js/';
		$params = $this->_params;

		$document = JFactory::getDocument();

		AriDocumentHelper::includeJsFile(JURI::root(true) . '/media/arismartcontent/holder/holder.js');
		$document->addScriptDeclaration(
			';Holder.add_theme("mediagallery", {background: "transparent", text: " "});'
		);
				
		AriDocumentHelper::includeJsFile($jsUri . 'gallery.js');
		AriDocumentHelper::includeCssFile($baseUri . 'css/style.css');

		$loaded = true;
	}

	function registerClientInstance($itemCount = 0)
	{
		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		$lightboxParams = AriUtils::getParam($params, 'lightbox');
		$lightboxPlugin = AriSmartContentWidgetMediaGalleryHelper::getLightboxPlugin($lightboxParams);
		$appHelper = AriSmartContentApplicationHelper::getInstance();

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

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

		$initCode = '';
		if ($lightboxPlugin)
		{
			$intPluginCode = $lightboxPlugin->getInitClientCode('#' . $id, null);

			if ($intPluginCode)
				$initCode .= sprintf(';$("#%1$s").on("mediagallery.changed", function() { %2$s });',
					$id,
					$intPluginCode
				);
		}
		
		$useHolderJs = true;
		if ($useHolderJs)
		{
			$initCode .= sprintf(';$("#%1$s").on("mediagallery.changed", function() { Holder.run({images:".ari-media-gallery-img"}); });',
				$id
			);
		}
		
		$initCode .= sprintf('var opts = %1$s;', !empty($jsOptions) ? json_encode($jsOptions) : '{}');
		$initCode .= sprintf('$("#%1$s").ARIMediaGallery(opts);', $id);

		$document = JFactory::getDocument();

		$width = AriUtils::getParam($mainParams, 'width');
		$layoutParams = AriUtils::getParam($params, 'layout');
		$itemWidth = trim(AriUtils::getParam($layoutParams, 'colwidth', ''));
		if (empty($itemWidth))
			$itemWidth = 'auto';

		$styles = '';
		if ($width)
			$styles .= sprintf(
				'#%1$s {max-width:%2$s}',
				$id,
				$width
			);
		
		$styles .= sprintf(
			'#%1$s .ari-media-gallery-item {width:%2$s}',
			$id,
			$itemWidth
		);
		
		$customStyles = AriUtils::getParam($mainParams, 'customstyle', '');
		if ($customStyles)
			$styles .= str_replace(
				array(
					'{$id}'
				),
				array(
					$id
				),
				$customStyles
			);

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

		if ($styles)
			$document->addStyleDeclaration($styles);

		if ($loadMethod == 'load')
			$document->addScriptDeclaration(';(window["ascJQuery"] || jQuery)(window).load(function() { var $ = window["ascJQuery"] || jQuery;' . $initCode . '});');
		else
			$document->addScriptDeclaration(';(window["ascJQuery"] || jQuery)(document).ready(function($) { ' . $initCode . '});');
	}

	function getJsOptions($itemCount = 0)
	{
		$params = $this->_params;
		$id = $this->getId();
		$options = AriUtils::getParam($params, 'widget');
		$pagingOptions = AriUtils::getParam($params, 'paging');

		$defOptions = array(
			'effect' => 'random',
			'slices' => 15,
		);

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

		$pagingEnabled = AriUtils::getParam($pagingOptions, 'enable') == 'paging_enable';
		if ($pagingEnabled)
		{
			$jsOptions['pagingEnabled'] = true;
			$jsOptions['paging'] = $this->getPagingJsOptions($itemCount);
		}

		return $jsOptions;
	}
	
	function getPagingJsOptions($itemCount = 0)
	{
		$pagingParams = $this->getPagingOptions();
		$params = $this->_params;
		$id = $this->getId();
		
		$defOptions = array(
			'currentPage' => 0,
		);
		$pagingOptions = AriUtils::getParam($params, 'paging');
		$pagingJsOptions = AriUtils::getParam($pagingOptions, 'options');
		
		$jsOptions = AriParametersHelper::getUniqueOverrideParameters($defOptions, $pagingJsOptions);
		
		$jsOptions['el'] = '#' . $id . ' .ari-media-gallery-paging';
		$jsOptions['pageSize'] = $pagingParams['pageSize'];
		$jsOptions['itemCount'] = $itemCount;
		
		if (isset($jsOptions['currentPage']) && $jsOptions['currentPage'] > 0)
			--$jsOptions['currentPage'];

		return $jsOptions;
	}
	
	function getPagingOptions()
	{
		$options = array(
			'enabled' => false,
		);
		
		$params = $this->_params;
		$pagingOptions = AriUtils::getParam($params, 'paging');
		$pagingJsOptions = AriUtils::getParam($pagingOptions, 'options');

		$options['enabled'] = AriUtils::getParam($pagingOptions, 'enable') == 'paging_enable';
		$pos = AriUtils::getParam($pagingOptions, 'position', 'bottom');
		if (empty($pos))
			$pos = 'bottom';
			
		$options['position'] = $pos;
		
		if (!$options['enabled'])
		{
			$options['pageSize'] = 0;
			$options['currentPage'] = 0;
		}
		else
		{
			$pageList = $this->getPageList(AriUtils::getParam($pagingOptions, 'pagelist'));
			
			$options['pageList'] = $pageList['list'];
			$options['pageSize'] = $pageList['pageSize'];
			
			$currentPage = intval(AriUtils::getParam($pagingJsOptions, 'currentPage', 0), 10) - 1;
			if ($currentPage < 0)
				$currentPage = 0;
			$options['currentPage'] = $currentPage;
		}
		
		return $options;
	}
	
	function getPageList($listOptions)
	{
		$list = array(
			'pageSize' => 0,
			'list' => array()
		);

		$listOptions = json_decode($listOptions);
		$pageList = array();
        if (is_array($listOptions))
        {
            foreach ($listOptions as $listOption)
            {
                $pageSize = AriUtils::getParam($listOption, 'size');
                if (empty($pageSize) && $pageSize !== '0')
                    continue;

                $pageSize = intval($pageSize, 10);
                if ($pageSize < 0)
                {
                    continue;
                }

                $pageLbl = @trim(AriUtils::getParam($listOption, 'lbl'));
                if (empty($pageLbl))
                    $pageLbl = $pageSize;

                $pageOption = new stdClass();
                $pageOption->text = $pageLbl;
                $pageOption->value = $pageSize;

                $pageList[$pageSize] = $pageOption;

                $isDefault = !is_null(AriUtils::getParam($listOption, 'def'));

                if ($isDefault)
                    $list['pageSize'] = $pageSize;
            }
        }

		$list['list'] = $pageList;

		if (count($pageList) > 0 && !isset($pageList[$list['pageSize']]))
		{
			$firstPageOption = reset($pageList);
			$list['pageSize'] = $firstPageOption->value;
		}

		return $list;
	}

	function render()
	{
	}
}