<?php
/**
* 2007-2014 PrestAddon
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestaddon.com for more information.
*
*  @author    PrestAddon SA <admin@prestaddon.com>
*  @copyright 2007-2014 PrestAddon
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

if (!defined('_PS_VERSION_'))
	exit;
class VtemSkitter extends Module
{
	public function __construct()
	{
		$this->name = 'vtemskitter';
		$this->tab = 'others';
		$this->version = '1.1';
		$this->author = 'PrestAddon';
		$this->need_instance = 0;
		$this->bootstrap = true;
		parent::__construct();
		$this->displayName = $this->l('VTEM Skitter');
		$this->description = $this->l('This is a flexible Prestashop slideshow module that comes with 40 unique and smooth animations.');
	}
	public function install()
	{
		if (!parent::install()
		|| !$this->registerHook('header')
		|| !$this->registerHook('displayTopColumn'))
			return false;
		$images = $this->parseImageDir();
		if (!$images)
			return false;
		$langs = '';
		$count_images = count($images);
		for ($i = 0; $i < $count_images; $i++)
			$langs .= 'all;';
		if (!Configuration::updateValue($this->name.'_autoplay', 1)
			|| !Configuration::updateValue($this->name.'_interval', 4000)
			|| !Configuration::updateValue($this->name.'_height', '40%')
			|| !Configuration::updateValue($this->name.'_width', '100%')
			|| !Configuration::updateValue($this->name.'_fx', 'random')
			|| !Configuration::updateValue($this->name.'_margin', '0px')
			|| !Configuration::updateValue($this->name.'_navstyle', 'none')
			|| !Configuration::updateValue($this->name.'_navposition', 'right')
			|| !Configuration::updateValue($this->name.'_nav', 1)
			|| !Configuration::updateValue($this->name.'_pauseonhover', 1)
			|| !Configuration::updateValue($this->name.'_keyboard', 1)
			|| !Configuration::updateValue($this->name.'_progressbar', 0)
			|| !Configuration::updateValue($this->name.'_links', '')
			|| !Configuration::updateValue($this->name.'_titles', '')
			|| !Configuration::updateValue($this->name.'_decss', '')
			|| !Configuration::updateValue($this->name.'_langs', $langs)
			|| !Configuration::updateValue($this->name.'_images', implode(';', $images)))
			return false;
		return true;
	}
	private function postProcess()
	{
		Configuration::updateValue($this->name.'_autoplay', Tools::getValue('autoplay'));
		Configuration::updateValue($this->name.'_interval', Tools::getValue('interval'));
		Configuration::updateValue($this->name.'_height', Tools::getValue('height'));
		Configuration::updateValue($this->name.'_width', Tools::getValue('width'));
		Configuration::updateValue($this->name.'_fx', Tools::getValue('fx'));
		Configuration::updateValue($this->name.'_margin', Tools::getValue('margin'));
		Configuration::updateValue($this->name.'_navstyle', Tools::getValue('navstyle'));
		Configuration::updateValue($this->name.'_navposition', Tools::getValue('navposition'));
		Configuration::updateValue($this->name.'_images', Tools::getValue('image_data'));
		Configuration::updateValue($this->name.'_links', Tools::getValue('link_data'));
		Configuration::updateValue($this->name.'_titles', Tools::getValue('title_data'));
		Configuration::updateValue($this->name.'_decss', Tools::getValue('decs_data'));
		Configuration::updateValue($this->name.'_langs', Tools::getValue('lang_data'));
		Configuration::updateValue($this->name.'_nav', Tools::getValue('nav'));
		Configuration::updateValue($this->name.'_pauseonhover', Tools::getValue('pauseonhover'));
		Configuration::updateValue($this->name.'_keyboard', Tools::getValue('keyboard'));
		Configuration::updateValue($this->name.'_progressbar', Tools::getValue('progressbar'));
	}
	public function getContent()
	{
		$output = '';
		$errors = array();
		if (Tools::isSubmit('submitSkitter'))
		{
			$ninterval = (int)Tools::getValue('interval');
			if (!$ninterval || $ninterval <= 0 || !Validate::isInt($ninterval))
				$errors[] = $this->l('An invalid number of products has been specified.');
			else
			$this->postProcess();
			if (isset($errors) && count($errors))
				$output .= $this->displayError(implode('<br />', $errors));
			else
				$output .= $this->displayConfirmation($this->l('Your settings have been updated.'));
		}
		return $output.$this->renderForm();
	}
	public function renderForm()
	{
		$this->context->controller->addJqueryPlugin('tablednd');
		$this->context->controller->addJS($this->_path.'/views/templates/admin/js/ajaxupload.js');
		$this->context->controller->addJS($this->_path.'/views/templates/admin/js/vtemskitter.js');
		$this->context->controller->addCSS($this->_path.'/views/templates/admin/css/admin.css');
		$fields_form = array(
			'form' => array(
				'legend' => array(
					'title' => $this->l('Settings'),
					'icon' => 'icon-cogs'
				),
				'input' => array(
					array(
						'type' => 'html',
						'name' => '<table id="hidden-row" style="display:none">'.$this->getTableRowHTML(0, 2, '').'</table>'
					),
					array(
						'type' => 'text',
						'label' => $this->l('Module width'),
						'name' => 'width',
						'class' => 'fixed-width-sm',
						'desc' => $this->l('Set container width for the slideshow in pixel[px] (ex : \'600px\') or percentage (ex : \'100%\')'),
					),
					array(
						'type' => 'text',
						'label' => $this->l('Module height'),
						'name' => 'height',
						'class' => 'fixed-width-sm',
						'desc' => $this->l('Here you can type pixels (for instance \'300px\'), or percentage (relative to the width, for instance \'50%\')'),
					),
					array(
						'type' => 'text',
						'label' => $this->l('Module margin'),
						'name' => 'margin',
						'class' => 'fixed-width-sm',
						'desc' => $this->l('Margin of the module in pixel (Top / Right / Bottom / Left)'),
					),
					array(
						'type' => (_PS_VERSION_ > 1.5) ? 'switch' : 'radio',
						'label' => $this->l('AutoPlay'),
						'desc' => $this->l('You can enable/disable the automatic animation of the items'),
						'name' => 'autoplay',
						'class' => 'child',
						'is_bool' => true,
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Yes')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('No')
							)
						),
					),
					array(
						'type' => 'text',
						'label' => $this->l('AutoPlay Delay'),
						'name' => 'interval',
						'class' => 'fixed-width-sm',
						'desc' => $this->l('Amount in milliseconds for the autoplay to change'),
					),
					array(
						'type' => 'select',
						'label' => $this->l('Effect'),
						'desc' => $this->l('Select a effect for the slideshow'),
						'name' => 'fx',
						'id' => 'fx',
						'options' => array(
							'query' => array(
								array('name' => 'cube'),
								array('name' => 'cubeRandom'),
								array('name' => 'block'),
								array('name' => 'cubeStop'),
								array('name' => 'cubeHide'),
								array('name' => 'cubeSize'),
								array('name' => 'horizontal'),
								array('name' => 'showBars'),
								array('name' => 'showBarsRandom'),
								array('name' => 'tube'),
								array('name' => 'fade'),
								array('name' => 'fadeFour'),
								array('name' => 'paralell'),
								array('name' => 'blind'),
								array('name' => 'blindHeight'),
								array('name' => 'blindWidth'),
								array('name' => 'directionTop'),
								array('name' => 'directionBottom'),
								array('name' => 'directionRight'),
								array('name' => 'directionLeft'),
								array('name' => 'cubeStopRandom'),
								array('name' => 'cubeSpread'),
								array('name' => 'cubeJelly'),
								array('name' => 'glassCube'),
								array('name' => 'glassBlock'),
								array('name' => 'random'),
								array('name' => 'randomSmart'),
								array('name' => 'glassBlock'),
								array('name' => 'glassCube'),
								array('name' => 'circlesRotate'),
								array('name' => 'circlesInside'),
								array('name' => 'circles'),
								array('name' => 'downBars'),
								array('name' => 'upBars'),
								array('name' => 'cubeShow'),
								array('name' => 'swapBarsBack'),
								array('name' => 'swapBars'),
								array('name' => 'hideBars'),
								array('name' => 'cut'),
								array('name' => 'swapBlocks')
							),
							'id' => 'name',
							'name' => 'name',
						)
					),
					array(
						'type' => 'select',
						'label' => $this->l('Navigation style'),
						'desc' => $this->l('Select a navigation style for the slideshow'),
						'name' => 'navstyle',
						'id' => 'navstyle',
						'options' => array(
							'query' => array(
								array('id' => 'numbers', 'name' => 'numbers'),
								array('id' => 'thumbs', 'name' => 'thumbs'),
								array('id' => 'dots', 'name' => 'dots'),
								array('id' => 'dots-preview', 'name' => 'dots-preview'),
								array('id' => 'none', 'name' => 'none'),
							),
							'id' => 'id',
							'name' => 'name',
						)
					),
					array(
						'type' => 'select',
						'label' => $this->l('Navigation position'),
						'desc' => $this->l('Select the position of navigation to display on the module'),
						'name' => 'navposition',
						'id' => 'navposition',
						'options' => array(
							'query' => array(
								array('id' => 'left', 'name' => 'left'),
								array('id' => 'center', 'name' => 'center'),
								array('id' => 'right', 'name' => 'right')
							),
							'id' => 'id',
							'name' => 'name',
						)
					),
					array(
						'type' => (_PS_VERSION_ > 1.5) ? 'switch' : 'radio',
						'label' => $this->l('Pause on hover'),
						'desc' => $this->l('If true, and autoPlay is enabled, the show will pause on hover'),
						'name' => 'pauseonhover',
						'class' => 'child',
						'is_bool' => true,
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Yes')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('No')
							)
						),
					),
					array(
						'type' => (_PS_VERSION_ > 1.5) ? 'switch' : 'radio',
						'label' => $this->l('Show Next/Prev'),
						'desc' => $this->l('Use to show/hide the Previous and Next buttons'),
						'name' => 'nav',
						'class' => 'child',
						'is_bool' => true,
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Yes')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('No')
							)
						),
					),

					array(
						'type' => (_PS_VERSION_ > 1.5) ? 'switch' : 'radio',
						'label' => $this->l('Enable keyboard move'),
						'desc' => $this->l('Move to next/previous image with keyboard arrows?'),
						'name' => 'keyboard',
						'class' => 'child',
						'is_bool' => true,
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Yes')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('No')
							)
						),
					),
					array(
						'type' => (_PS_VERSION_ > 1.5) ? 'switch' : 'radio',
						'label' => $this->l('Progress bar'),
						'desc' => $this->l('Show/Hide progress bar on the module'),
						'name' => 'progressbar',
						'class' => 'child',
						'is_bool' => true,
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Yes')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('No')
							)
						),
					),
					array(
						'type' => 'html',
						'name' => $this->renderImage()
					)
				),
				'submit' => array(
					'title' => $this->l('Save'),
					'class' => 'button'
				)
			)
		);
		$helper = new HelperForm();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$this->fields_form = array();
		$helper->id = (int)Tools::getValue('id_carrier');
		$helper->identifier = $this->identifier;
		$helper->submit_action = 'submitSkitter';
		$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->tpl_vars = array(
			'fields_value' => $this->getConfigFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);
		return $helper->generateForm(array($fields_form));
	}
	public function getConfigFieldsValues()
	{
		return array(
			'width' => Tools::getValue('width', Configuration::get($this->name.'_width')),
			'height' => Tools::getValue('height', Configuration::get($this->name.'_height')),
			'margin' => Tools::getValue('margin', Configuration::get($this->name.'_margin')),
			'autoplay' => Tools::getValue('autoplay', Configuration::get($this->name.'_autoplay')),
			'interval' => Tools::getValue('interval', Configuration::get($this->name.'_interval')),
			'fx' => Tools::getValue('fx', Configuration::get($this->name.'_fx')),
			'navstyle' => Tools::getValue('navstyle', Configuration::get($this->name.'_navstyle')),
			'navposition' => Tools::getValue('navposition', Configuration::get($this->name.'_navposition')),
			'pauseonhover' => Tools::getValue('pauseonhover', Configuration::get($this->name.'_pauseonhover')),
			'nav' => Tools::getValue('nav', Configuration::get($this->name.'_nav')),
			'keyboard' => Tools::getValue('keyboard', Configuration::get($this->name.'_keyboard')),
			'progressbar' => Tools::getValue('progressbar', Configuration::get($this->name.'_progressbar'))
		);
	}
	public function renderImage()
	{
		$dir_images = $this->parseImageDir();
		$conf_images = $this->getImageArray();
		$nb_dir_images = count($dir_images);
		$nb_conf_images = count($conf_images);
		$render = '<input type="hidden" id="hidden_image_data" name="image_data" value="'.Configuration::get($this->name.'_images').'"/>
					<input type="hidden" id="hidden_link_data" name="link_data" value="'.Configuration::get($this->name.'_links').'"/>
					<input type="hidden" id="hidden_title_data" name="title_data" value="'.Configuration::get($this->name.'_titles').'"/>
					<input type="hidden" id="hidden_decs_data" name="decs_data" value="'.Configuration::get($this->name.'_decss').'"/>
					<input type="hidden" id="hidden_lang_data" name="lang_data" value="'.Configuration::get($this->name.'_langs').'"/>';
		$render .= '<div class="panel panel_images"><h3>'.$this->l('Images Manager').
		'<a href="#" id="uploadImage" class="btn btn-default pull-right"><img src="../img/admin/add.gif" alt="upload image" />&nbsp;'.
		$this->l('Add an image').'</a>
                    <img id="loading_gif" src="../img/admin/ajax-loader.gif" alt="uploading..." style="display:none;"/></h3>
					<table cellpadding="0" cellspacing="0" class="table space'.($nb_dir_images >= 2 ? ' tableDnD' : '' )
					.'" id="table_images" style="min-width:825px;">
					<thead><tr class="nodrag nodrop">
						<th width="60" colspan="2">'.$this->l('Position').'</th>
						<th style="padding-left: 10px;">'.$this->l('Image').'</th>
						<th width="120">'.$this->l('Link').'</th>
						<th width="150">'.$this->l('Title').'</th>
						<th width="150">'.$this->l('Description').'</th>
						<th width="80">'.$this->l('Language').'</th>
						<th width="40">'.$this->l('Enabled').'</th>
						<th width="40">'.$this->l('Delete').'</th>
					</tr></thead>';
		if ($nb_dir_images)
		{
			$i = 1;
			foreach ($conf_images as $conf_image)
			{
				if (in_array($conf_image['name'], $dir_images))
				{
					$render .= $this->getTableRowHTML($i, $nb_dir_images, $conf_image['name'], $conf_image['link'], $conf_image['title'], $conf_image['decs'], true);
					$i++;
				}
			}
			if ($nb_dir_images > $nb_conf_images)
			{
				foreach ($dir_images as $dir_image)
				{
					if (!$this->isImageInArray($dir_image, $conf_images))
					{
						$render .= $this->getTableRowHTML($i, $nb_dir_images, $dir_image);
						$i++;
					}
				}
			}
		}
		else
			$render .= '<tr><td colspan="4">'.$this->l('No image in module directory').'</td></tr>';
		$render .= '</table></div>';
		return $render;
	}
	public function processHook($modpos = 'top')
	{
		$this->smarty->assign(array('images' => $this->getImageArray(true),
						'modpos' => 'top',
						'autoplay' => Configuration::get($this->name.'_autoplay'),
						'interval' => Configuration::get($this->name.'_interval'),
						'height' => Configuration::get($this->name.'_height'),
						'width' => Configuration::get($this->name.'_width'),
						'fx' => Configuration::get($this->name.'_fx'),
						'margin' => Configuration::get($this->name.'_margin'),
						'navstyle' 	=> Configuration::get($this->name.'_navstyle'),
						'pauseonhover' => Configuration::get($this->name.'_pauseonhover'),
						'keyboard' 	=> Configuration::get($this->name.'_keyboard'),
						'progressbar' => Configuration::get($this->name.'_progressbar'),
						'navposition' => Configuration::get($this->name.'_navposition'),
						'nav' => Configuration::get($this->name.'_nav')));
						return $this->display(__FILE__, 'vtemskitter.tpl');
	}
	public function hookdisplayTopColumn($params)
	{
		return $this->processHook($params, 'top');
	}
	public function hookHome($params)
	{
		return $this->processHook($params, 'home');
	}
	public function hookFooter($params)
	{
		return $this->processHook($params, 'footer');
	}
	public function hookrightColumn($params)
	{
		return $this->processHook($params, 'rightColumn');
	}
	public function hookleftColumn($params)
	{
		return $this->processHook($params, 'leftColumn');
	}
	public function hookHeader()
	{
		$this->context->controller->addJS(($this->_path).'views/templates/hook/js/jquery-ui-1.8.23.custom.min.js');
		$this->context->controller->addJS(($this->_path).'views/templates/hook/js/jquery.skitter.js');
		$this->context->controller->addCSS(($this->_path).'views/templates/hook/css/styles.css', 'all');
	}
	private function getImageArray($lang_filter = false)
	{
		$images = explode(';', Configuration::get($this->name.'_images'));
		$links 	= explode(';', Configuration::get($this->name.'_links'));
		$titles 	= explode(';', Configuration::get($this->name.'_titles'));
		$decss 	= explode(';', Configuration::get($this->name.'_decss'));
		$langs 	= $lang_filter ? explode(';', Configuration::get($this->name.'_langs')) : false;
		$tab_images = array();
		for ($i = 0, $length = count($images); $i < $length; $i++)
		{
			if ($images[$i] != '')
			{
				if ($lang_filter && isset($langs[$i]) && $langs[$i] != 'all' && $langs[$i] != $this->context->language->id)
					continue;
				$tab_images[] = array('name' => $images[$i],
										'link' => isset($links[$i]) ? $links[$i] : '',
										'title' => isset($titles[$i]) ? $titles[$i] : '',
										'decs' => isset($decss[$i]) ? $decss[$i] : '');
			}
		}
		return $tab_images;
	}
	private function isImageInArray($name, $array)
	{
		if (!is_array($array))
			return false;
		foreach ($array as $image)
		{
			if (isset($image['name']))
			{
				if ($image['name'] == $name)
					return true;
			}
		}
		return false;
	}
	private function parseImageDir()
	{
		$dir = _PS_MODULE_DIR_.$this->name.'/img/';
		$imgs = array();
		if ($dh = opendir($dir))
		{
			while (($file = readdir($dh)) !== false)
			{
				if (!is_dir($file) && preg_match('/^[^.].*?\.(jpe?g|gif|png)$/i', $file))
					array_push($imgs, $file);
			}
			closedir($dh);
		}
		else
		{
			echo 'can\'t open slide directory';
			return false;
		}
		return $imgs;
	}
	private function getTableRowHTML($i, $nbimages, $imagename, $imagelink = '', $imagetitle = '', $imagedecs = '', $checked = false)
	{
		return '<tr id="tr_image_'.$i.'"'.($i % 2 ? ' class="alt_row"' : '').' style="height: 42px;">
				<td class="positions" width="30" style="padding-left: 20px;">'.$i.'</td>
				<td'.($nbimages >= 2 ? ' class="dragHandle"' : '').' id="td_image_'.$i.'" width="30">'
					.(_PS_VERSION_ > 1.5 ? '<div class="dragGroup">&nbsp;</div>' : '
					<a'.($i == 1 ? ' style="display: none;"' : '' ).' href="#" class="move-up">
					<img src="../img/admin/up.gif" alt="'.$this->l('Up').'" title="'.$this->l('Up').'" /></a><br />
					<a '.($i == $nbimages ? ' style="display: none;"' : '' ).'href="#" class="move-down">
					<img src="../img/admin/down.gif" alt="'.$this->l('Down').'" title="'.$this->l('Down').'" /></a>').'
				</td>
				<td class="imagename" style="padding-left: 10px;">'.$imagename.'</td>
				<td class="imagelink">
					<input type="text" style="width: 100px" name="image_link_'.$i.'" value="'.$imagelink.'" />
				</td>
				<td class="imagetitle">
					<input type="text" style="width: 150px" name="image_title_'.$i.'" value="'.$imagetitle.'" />
				</td>
				<td class="imagedecs">
					<input type="text" style="width: 150px" name="image_decs_'.$i.'" value="'.$imagedecs.'" />
				</td>
				<td class="imagelang">'.$this->getLanguageSelectHTML($i).'</td>
				<td class="checkbox_image_enabled" style="padding-left: 25px;" width="40">
					<input type="checkbox" name="image_enable_'.$i.'"'.($checked ? ' checked="checked"' : '').' /> 
				</td>
				<td class="delete_image" style="padding-left: 25px;" width="40">
					<img src="../img/admin/disabled.gif" alt="'.$this->l('Delete').'" title="'.$this->l('Delete').'" style="cursor:pointer;" /> 
				</td>
			</tr>';
	}
	private function getLanguageSelectHTML($i)
	{
	$languages = Language::getLanguages();
	$langs = explode(';', Configuration::get($this->name.'_langs'));
	$html = '<select name="language_'.$i.'" style="width:55px">';
	$html .= '<option value="all">ALL</option>';
	foreach ($languages as $language)
		$html .= '<option value="'.$language['id_lang'].'"'
		.(isset($langs[$i - 1]) && $langs[$i - 1] == $language['id_lang'] ? 'selected="selected"' : '').'>'
		.Tools::strtoupper($language['iso_code']).'</option>';
	return $html .= '</select>';
	}
}
?>