<?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('Web.JSON.JSON');
AriKernel::import('Document.DocumentHelper');
AriKernel::import('Utils.ArrayHelper');
AriKernel::import('Web.HtmlHelper');
AriKernel::import('Web.Request');

class AriSmartContentWidgetSexyLightbox extends AriSmartContentWidget
{
	var $_params;
    private static $_autoLoadEnabled = false;

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

	function loadAssets($cssClass = null)
	{
		$this->loadMainAssets();

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

        $autoShow = (bool)AriUtils::getParam($mainParams, 'autoShow');
        if ($autoShow)
            $this->initAutoShow($cssClass);
	}

    function loadMainAssets()
    {
        static $loaded;

        if ($loaded)
            return ;

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

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

        AriDocumentHelper::includeJsFile($jsUri . 'jquery.sexylightbox.min.js');
        AriDocumentHelper::includeJsFile($jsUri . 'tools.js');

        $lang = JFactory::getLanguage();
        if ($lang->isRTL())
            AriDocumentHelper::includeCssFile($cssUri . 'sexylightbox_rtl.css');

        AriDocumentHelper::includeCustomHeadTag(sprintf('<!--[if lt IE 7]><link rel="stylesheet" href="%s" type="text/css" /><![endif]-->',
            $cssUri . 'sexylightbox.ie6.css'));
        AriDocumentHelper::includeCustomHeadTag(sprintf('<link rel="stylesheet" href="%s" type="text/css" />',
            $cssUri . 'sexylightbox.css'));
        AriDocumentHelper::includeCustomHeadTag(sprintf('<!--[if IE]><link rel="stylesheet" href="%s" type="text/css" /><![endif]-->',
            $cssUri . 'sexylightbox.ie.css'));

        $options = AriUtils::getParam($params, 'opt');

        $jsOptions = $this->getJsOptions($options);
        $document = JFactory::getDocument();
        $document->addScriptDeclaration(
            sprintf(
                ';(window["ascJQuery"] || jQuery)(document).ready(function(){ SexyLightbox.initialize(%s); });',
                !empty($jsOptions) ? json_encode($jsOptions) : ''
            )
        );

        $loaded = true;
    }

    function initAutoShow($cssClass)
    {
        if (self::$_autoLoadEnabled)
            return ;

        $mainParams = AriUtils::getParam($this->_params, '_default');
        $autoShow = AriUtils::getParam($mainParams, 'autoShow');
        $key = AriUtils::getParam($mainParams, 'key');

        if ($autoShow == 'once' && $key)
        {
            $cookieParams = AriUtils::getParam($this->_params, 'cookie');

            $cookieKey = 'asc_slb_' . $key;
            $cookieDuration = floatval(AriUtils::getParam($cookieParams, 'duration', 365)) * 24 * 60 * 60;

            if ($cookieDuration == 0)
            {
                if (!empty($_SESSION[$cookieKey]))
                    $autoShow = false;
                else
                    $_SESSION[$cookieKey] = true;
            }
            else
            {
                if (!empty($_COOKIE[$cookieKey]))
                    $autoShow = false;
                else
                    setcookie($cookieKey, '1', time() + $cookieDuration);
            }
        }
        else
            $autoShow = (bool)$autoShow;

        if (!$autoShow)
            return ;

        $autoCloseDelay = intval(AriUtils::getParam($mainParams, 'autoCloseDelay'), 10);

        $document = JFactory::getDocument();
        $document->addScriptDeclaration(
            sprintf(
                ';(window["ascJQuery"] || jQuery)(document).ready(function($){ setTimeout(function() { $(".%1$s").eq(0).click();%2$s }, 5); });',
                $cssClass,
                $autoCloseDelay > 0
                    ? sprintf('setTimeout(function() { SexyLightbox.close(); }, %1$d);', $autoCloseDelay * 1000)
                    : ''
            )
        );

        self::$_autoLoadEnabled = true;
    }

	function getJsOptions($overrideOptions = array())
	{
		$defOptions = array(
			'showDownloadLink' => false,
			'hoverDownloadLink' => true,
			'downloadLinkTitle' => 'Open the image in new window',
			'disableRightClick' => false,
			'enableShow' => false,
			'pauseDuration' => 5000,
			'autoStart' => false,
			'continiousShow' => false,
			'continious' => false,
			'find' => 'sexylightbox',
			'zIndex' => 32000,
			'color' => 'black',
			'emergefrom' => 'top',
			'showDuration' => 200,
			'closeDuration' => 400,
			'moveDuration' => 1000,
			'moveEffect' => 'easeInOutBack',
			'resizeDuration' => 1000,
			'resizeEffect' => 'easeInOutBack',
			'movieAutoPlay' => false,
			'wMode' => 'transparent',
			'shake' => array(
				'distance' => 10,
                'duration' => 100,
                'loops' => 2,
                'transition' => 'easeInOutBack'
            )
		);

		$jsOptions = AriParametersHelper::getUniqueOverrideParameters($defOptions, $overrideOptions);
		$jsOptions['dir'] = str_replace(' ', '%20', JURI::root(true)) . '/media/arismartcontent/sexylightbox/css/sexyimages';

		if (!empty($overrideOptions['overlayStyle']))
		{
			$fixOverlayStyle = array();
			$overlayStyle = $overrideOptions['overlayStyle'];
			foreach ($overlayStyle as $key => $value)
			{
				if (!is_null($value) && strlen($value) > 0)
					$fixOverlayStyle[$key] = $value;
			}

			$jsOptions['overlayStyle'] = $fixOverlayStyle;
		}

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

		$type = AriUtils::getParam($mainParams, 'type');

		if (empty($type))
		{
			echo '"ARI Smart Content - Sexy Lightbox": content type is not specified.';
			return ;
		}

 		$type = strtolower($type);
		$contentHandler = 'contentHandler_' . $type;
		if (!method_exists($this, $contentHandler))
		{
			echo sprintf('"ARI Smart Content - Sexy Lightbox": unsupported content type ("%1$s").', $type);
			return ;
		}

        if (!isset($this->_params['_default']['class']))
            $this->_params['_default']['class'] = '';

        $cssClass = uniqid('slb_', false);
        $this->_params['_default']['class'] .= ' ' . $cssClass;

		$this->loadAssets($cssClass);
		echo $this->$contentHandler(AriUtils::getParam($this->_params, $type));
	}
	
	function contentHandler_url($params)
	{
		$urlList = preg_split('/[\s]+/i', $params['url']);
		
		$links = array();
		
		foreach ($urlList as $url)
		{
			$uri = new JURI($url);
			$path = $uri->getPath();

			// if not image
			if (!preg_match('/\.(jpg|jpeg|png|bmp|gif)$/i', $path))
			{
				$uri->setVar('TB_iframe', '1');
			}
			else
			{
				$uri->setVar('force', 'image');
			}

			$links[] = array(
				'url' => $uri->toString()
			);
		}
		
		return $this->generateLinks($links);
	}
	
	function contentHandler_image($params)
	{
		$urlList = preg_split('/[\s]+/i', $params['src']);
		
		$links = array();
		
		foreach ($urlList as $url)
		{
			$links[] = array(
				'url' => $url
			);
		}
		
		return $this->generateLinks($links, 'image');
	}

	function contentHandler_article($params)
	{
		$idList = preg_split('/[\s;,]+/i', $params['id']);
		$idList = AriArrayHelper::toInteger($idList, 1);
		
		$links = array();
		
		foreach ($idList as $id)
		{
			$links[] = array(
				'url' => 'index.php?option=com_content&view=article&id=' . $id . '&tmpl=component&TB_iframe=1'
			);
		}
		
		return $this->generateLinks($links);
	}
	
	function contentHandler_youtube($params)
	{
		$idList = preg_split('/[\s;,]+/i', $params['id']);
		$protocol = AriRequest::getProtocol();

		$links = array();

		foreach ($idList as $id)
		{
			$links[] = array(
				'url' => $protocol . 'www.youtube.com/watch?v=' . $id
			);
		}

		return $this->generateLinks($links);
	}

	function contentHandler_inline($params)
	{
		$content = $params['content'];
		$id = uniqid('inline_', false);
		
		$links = array(
			array(
				'url' => '?inlineId=' . $id . '#TB_inline'
			)
		);

		return sprintf(
			'<div id="%2$s" class="sexy-icontent" style="display:none;">%1$s</div>%3$s',
			$content,
			$id,
			$this->generateLinks($links)
		);
	}
	
	function contentHandler_vimeo($params)
	{
		$idList = preg_split('/[\s;,]+/i', $params['id']);
		$protocol = AriRequest::getProtocol();
		
		$links = array();

		foreach ($idList as $id)
		{
			$links[] = array(
				'url' => $protocol . 'www.vimeo.com/' . $id
			);
		}

		return $this->generateLinks($links);
	}

	function contentHandler_module($params)
	{
		$idList = preg_split('/[\s;,]+/i', $params['id']);
		$idList = AriArrayHelper::toInteger($idList, 1);

		$links = array();

		foreach ($idList as $id)
		{		
			AriSmartContentApplicationHelper::addTrustedModule($id);

			$links[] = array(
				'url' => 'index.php?option=com_arismartcontent&view=module&tmpl=component&module=' . $id . '&TB_iframe=true'
			);
		}

		return $this->generateLinks($links);
	}

	function generateLinks($links, $force = null)
	{
		$content = '';
		if (!is_array($links) || count($links) == 0)
			return $content;

		$params = $this->_params;
		$mainParams = AriUtils::getParam($params, '_default');
		$linkText = AriUtils::getParam($mainParams, 'link');
		$width = AriUtils::getParam($mainParams, 'width', '800');
		$height = AriUtils::getParam($mainParams, 'height', '600');
		$cssClass = AriUtils::getParam($mainParams, 'class');
		$bgColor = AriUtils::getParam($mainParams, 'bgColor');
		$modal = (bool)AriUtils::getParam($mainParams, 'modal');
		$group = AriUtils::getParam($mainParams, 'group');
		$title = AriUtils::getParam($mainParams, 'title');

		if (count($links) > 0 && !$group)
			$group = uniqid('gr_', false);

		$rel = 'sexylightbox' . ($group ? '[' . $group . ']' : ''); 

		for ($i = 0; $i < count($links); $i++)
		{
			$link = $links[$i];
			$linkAttrs = array();

			$uri = new JURI($link['url']);
			
			$linkForce = $uri->getVar('force');
			
			if ($force != 'image' && $linkForce != 'image')
			{
				$uri->setVar('width', $width);
				$uri->setVar('height', $height);
			}

			if ($modal)
				$uri->setVar('modal', 1);

			if ($bgColor)
				$uri->setVar('background', $bgColor);
				
			$linkAttrs['href'] = $uri->toString();
			$linkAttrs['rel'] = $rel;
			$linkAttrs['class'] = $cssClass . ($i > 0 ? ' sexybox-hidden' : '');
			
			if ($title)
				$linkAttrs['title'] = $title;

			$content .= sprintf('<a%1$s>%2$s</a>',
				AriHtmlHelper::getAttrStr($linkAttrs),
				$i == 0 ? $linkText : ''
			);
		}

		return $content;
	}
}