<?php

/**
  * Slideshow module, homeslideshow.php 
  *
  * @author Tiagop <contact@tiagop.com>
  * @copyright Tiagop
  * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
  * @version 1.0
 **/
  
class Homeslideshow extends Module
{	
	private $_html = '';
	
	public $xml_file = "/modules/homeslideshow/slideshow.xml";
	public $save_path = "/modules/homeslideshow/img/";
	public $supported_formats = array("png","jpg","jpeg","gif","JPG","GIF","JPEG","PNG");

	public $preferences = array();
	
	public $default_values = array("panel_width" => 550,
									"panel_height" => 220,
									"show_overlay" => 1,
									"overlay_position" => "bottom",
									"frame_width" => 50,
									"frame_height" => 50,
									"transition_interval" => 4000,
									"background_color" => "#ffffff",
									"border_color" => "#aaaaaa",
									"filmstrip_selected_border" => "#cccccc",
									"show_filmstrip" => 1,
									"filmstrip_position" => "bottom",
									"overlay_height" => 70,
									"panel_number" => 7
								);
	function __construct()
	{
		$this->name = 'homeslideshow';
 	 	$this->version = '1.2';
 	 	$this->tab = 'Tools';

		$this->preferences = self::getPreferences();
		
		parent::__construct();
		
		$this->displayName = $this->l('Homepage slideshow');
		$this->description = $this->l('Display a slideshow on homepage');
	}
	
	public function install()
	{
	 	if (!parent::install()) return false;
	 	
		/**** create tab ****/
		$tab = new Tab();
		$tab->class_name = "AdminHomeslideshow";
		$tab->module = "homeslideshow";
		$tab->id_parent = Tab::getCurrentTabId(); 
		
		$langs = Language::getLanguages();
		foreach($langs as $l){
			if($l['iso_code'] == 'fr'){
				$tab->name[$l['id_lang']] = "Diaporama";
			}else{
				$tab->name[$l['id_lang']] = "Slideshow";
			}
		}
		$id = $tab->add(true,false);
		copy(_PS_ROOT_DIR_."/modules/homeslideshow/AdminHomeslideshow.gif",_PS_ROOT_DIR_."/img/t/AdminHomeslideshow.gif");
		Configuration::updateValue('SLIDESHOW_PREFERENCES',serialize($this->default_values));
		$this->registerHook('top'); //to add css file in <head>
		return $this->registerHook('home');
	}
	
	public function uninstall()
	{
		if (!Configuration::deleteByName('SLIDESHOW_PREFERENCES') OR !parent::uninstall()) return false;
		$row = Db::getInstance()->getRow('SELECT `id_tab` FROM '._DB_PREFIX_.'tab WHERE `class_name` = "AdminHomeslideshow" AND `module` = "homeslideshow"');
		if($row){
			$tab = new Tab($row['id_tab']);
			$tab->delete();
		}
		@unlink(_PS_ROOT_DIR_."/img/t/AdminHomeslideshow.gif");
		return true;
	}
	
	public function hookTop($params){
		global $css_files;
		$css_files[$this->_path.'style.css'] = 'all';
	}

	public function hookHome($params){
		global $smarty, $cookie, $css_files;
		
		$xml = simplexml_load_file(_PS_ROOT_DIR_.$this->xml_file);
		$lang_iso = Language::getIsoById(intval($cookie->id_lang));
		$slides = array();
		$i = 0;
		foreach($xml->slide as $item){
			$slides[$i]['link'] = (string) $item['link'];
			$slides[$i]['img'] = (string) $item['img'];
			$desc = $xml->xpath("//slide[".($i+1)."]/lang[@name='".$lang_iso."']");
			$slides[$i]['desc'] = nl2br((string) $desc[0]);
			$slides[$i]['title'] = nl2br((string) $desc[0]['title']);
			$i++;
		}
		
		$smarty->assign(array('pref' => $this->preferences,'default' => $this->default_values,'slides' => $slides));
		
		return $this->display(__FILE__, 'homeslideshow.tpl');
	}
	
	private function _postProcess()
	{
		if (Tools::isSubmit('submitHomeslideshow'))
		{
			$pref = $_POST['pref'];
			
			if(!isset($pref['show_filmstrip'])) $pref['show_filmstrip'] = 0;
			if(!isset($pref['show_overlay'])) $pref['show_overlay'] = 0;
			
			$pref_serialize = serialize($pref);
			Configuration::updateValue('SLIDESHOW_PREFERENCES',$pref_serialize);
		}
		$this->_html .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('ok').'" /> '.$this->l('Settings updated').'</div>';
	}
	
	private function _displayForm()
	{
	
		$values = !empty($_POST) ? Tools::getValue('pref') : $this->preferences;
	
		$this->_html .=
		'<script type="text/javascript">
			function showHide(divid){
				if($("#"+divid).css("display") == "none") $("#"+divid).css("display","block"); 
				else $("#"+divid).css("display","none");
			}
		</script>
		
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
			<fieldset>
			<legend>'.$this->l('Slideshow preferences').'</legend>';
							
			$this->_html .= '
				<label>'.$this->l('Maximum number of panels').'</label>
				<div class="margin-form">
				<input type="text" name="pref[panel_number]" value="'.$values['panel_number'].'" size="1" />
				</div>
				
				<br /><div class="clear"></div>
				
				<label>'.$this->l('slideshow size').'</label>
				<div class="margin-form">
				&nbsp;&nbsp; '.$this->l('Width').' <input type="text" name="pref[panel_width]" value="'.$values['panel_width'].'" size="3" /> px
				&nbsp;&nbsp; '.$this->l('Height').' <input type="text" name="pref[panel_height]" value="'.$values['panel_height'].'" size="3" /> px
				</div>
				
				<br /><div class="clear"></div>
				
				<label>'.$this->l('Display title and description').'</label>
				<div class="margin-form">
				<input type="checkbox" onclick="showHide(\'overlay_position\');" name="pref[show_overlay]" value="1" '.(isset($values['show_overlay']) && $values['show_overlay'] == '1' ? 'checked' : '').' />
				</div>
				
				<br /><div class="clear"></div>
				
				<div id="overlay_position" style="display:'.((isset($values['show_overlay']) && $values['show_overlay'] == '1') ? '' : 'none').'">
				
				<!--
					<label>Position du cadre de description</label> 
					<div class="margin-form">
					'.$this->l('Top').' <input type="radio" name="pref[overlay_position]" value="top" '.((isset($values['overlay_position']) && $values['overlay_position'] == 'top') || !isset($values['overlay_position']) ? 'checked' : '').' /> 
					&nbsp; '.$this->l('Bottom').' <input type="radio" name="pref[overlay_position]" value="bottom" '.(isset($values['overlay_position']) && $values['overlay_position'] == 'bottom' ? 'checked' : '').' />
					</div>
				-->
					
					<label>'.$this->l('Overlay height').'</label>
					<div class="margin-form">
					<input type="text" name="pref[overlay_height]" value="'.$values['overlay_height'].'" size="3" /> px
					</div>
					
				</div>
					
				<br /><div class="clear"></div>
				
				<label>'.$this->l('Display Filmstrip').'</label>  
				<div class="margin-form">
				<input type="checkbox" onclick="showHide(\'filmstrip_position\');" name="pref[show_filmstrip]" value="1" '.((isset($values['show_filmstrip']) && $values['show_filmstrip'] == '1') ? 'checked' : '').'/>
				</div>
				
				<br /><div class="clear"></div>
				
				<div id="filmstrip_position" style="display:'.((isset($values['show_filmstrip']) && $values['show_filmstrip'] == '1') ? '' : 'none').'">
					<label>'.$this->l('Filmstrip position').'</label> 
					<div class="margin-form">
					'.$this->l('Top').' <input type="radio" name="pref[filmstrip_position]" value="top" '.((isset($values['filmstrip_position']) && $values['filmstrip_position'] == 'top') || !isset($values['filmstrip_position']) ? 'checked' : '').' /> 
					&nbsp; '.$this->l('Bottom').' <input type="radio" name="pref[filmstrip_position]" value="bottom" '.(isset($values['filmstrip_position']) && $values['filmstrip_position'] == 'bottom' ? 'checked' : '').' />
					</div>
					
					<br /><div class="clear"></div>
				
					<label>'.$this->l('Frames size').'</label>
					<div class="margin-form">
					&nbsp;&nbsp; '.$this->l('Width').' <input type="text" name="pref[frame_width]" value="'.$values['frame_width'].'" size="3" /> px
					&nbsp;&nbsp; '.$this->l('Height').' <input type="text" name="pref[frame_height]" value="'.$values['frame_height'].'" size="3" /> px
					</div>
					
					<br /><div class="clear"></div>
					
					<label>'.$this->l('Frame selected Border color').'</label> 
						<div class="margin-form">
						<input type="text" name="pref[filmstrip_selected_border]" value="'.$values['filmstrip_selected_border'].'" size="7" /><br /> 
						<p style="clear:both">'.$this->l('If empty, css property in /homeslideshow/style.css file will be used').'</p>
					</div>
					
				</div>
				
				<br /><div class="clear"></div>
				
				<label>'.$this->l('Transition interval').'</label> 
				<div class="margin-form">
				<input type="text" name="pref[transition_interval]" value="'.$values['transition_interval'].'" size="3"  /> '.$this->l('Seconds').'
				</div>
				
				<br /><div class="clear"></div>
				
				<label>'.$this->l('Background color').'</label> 
				<div class="margin-form">
				<input type="text" name="pref[background_color]" value="'.$values['background_color'].'" size="7" />
				<p style="clear:both">'.$this->l('If empty, css property in /homeslideshow/style.css file will be used').'</p>
				</div>
				
				<label>'.$this->l('Border color').'</label> 
				<div class="margin-form">
				<input type="text" name="pref[border_color]" value="'.$values['border_color'].'" size="7" /><br /> 
				<p style="clear:both">'.$this->l('If empty, css property in /homeslideshow/style.css file will be used').'</p>
				</div>
				
				<input class="button" name="submitHomeslideshow" value="'.$this->l('Update settings').'" type="submit" />
				
			</table>
		
			</fieldset>
		</form>';
	}
	
	public function getContent()
	{
		$this->_html = '<h2>'.$this->l('Slideshow settings').'</h2>';
		$this->_html .= '<p>'.$this->l('If you want to add slides, you must go to the slideshow sub tab on the navigation menu').'</p>';
		if (!empty($_POST))
		{
			$this->_postValidation();
			if (!isset($this->_postErrors) || !sizeof($this->_postErrors)){
				$this->_postProcess();
			}else{
				foreach ($this->_postErrors AS $err)
					$this->_html .= '<div class="alert error">'. $err .'</div>';
			}
		}else{
			$this->_html .= '<br />';
		}
		$this->_displayForm();
		return $this->_html;
	}
	
	private function _postValidation()
	{
		if (isset($_POST['submitHomeslideshow']))
		{
			if (empty($_POST['pref']['panel_width']) || !is_numeric($_POST['pref']['panel_width']))
				$this->_postErrors[] = $this->l('Numeric width is required for panel.');
			if (empty($_POST['pref']['panel_height']) || !is_numeric($_POST['pref']['panel_height']))
				$this->_postErrors[] = $this->l('Numeric height is required for panel.');
			if (empty($_POST['pref']['frame_width']) || !is_numeric($_POST['pref']['frame_width']))
				$this->_postErrors[] = $this->l('Numeric width is required for frames');
			if (empty($_POST['pref']['frame_height']) || !is_numeric($_POST['pref']['frame_height']))
				$this->_postErrors[] = $this->l('Numeric height is required for frames.');
			if (empty($_POST['pref']['transition_interval']) || !is_numeric($_POST['pref']['transition_interval']))
				$this->_postErrors[] = $this->l('Numeric number is required for transition delay.');
		}
	}


	public static function getPreferences(){
		$config = Configuration::get('SLIDESHOW_PREFERENCES');
		return unserialize($config); 	
	}	
	
	public function adminTabExec($token){
		
		global $currentIndex, $cookie;

		$defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT'));
		$languages = Language::getLanguages();
		$divLangName = "title&curren;name";
		$this->xml = simplexml_load_file(_PS_ROOT_DIR_.$this->xml_file);
		
		echo '<script type="text/javascript">
				id_language = Number('.$defaultLanguage.');
					function showHide(divid){
						if($("#"+divid).css("display") == "none") $("#"+divid).show("fast"); 
						else $("#"+divid).hide("fast");
					}
			  </script>
			  
				<fieldset class="width5"><legend><img src="../img/admin/world.gif" />'.$this->l('Slideshow').'</legend>';
			
			if(count($this->xml->slide) < $this->preferences["panel_number"]){
			
			 echo '<a href="#" onclick="showHide(\'submitAddDiv\'); return false;">'.$this->l('Add new slide').' <img src="../img/admin/add.gif" alt="add" /></a><br /><br />';
		
		echo '<div id="submitAddDiv" style="'.(!isset($_GET['submitAddSlide']) ? 'display:none;' : '').'">
			  <form name="formAddSlide" action="'.$currentIndex.'&submitAddSlide&token='.$token.'" method="post" enctype="multipart/form-data">
					
				<label>'.$this->l('File :').'</label>
				<div class="margin-form">
				<input type="hidden" name="MAX_FILE_SIZE" value="307200" />
				<input type="file" name="slidefile" />
				<p class="clear">.png, .jpg, .gif - '.$this->l('size advice').' '.$this->preferences["panel_width"].'px  X  '.$this->preferences["panel_height"].'px</p>
				</div>';
	
	if(isset($this->preferences["show_overlay"]) && $this->preferences["show_overlay"] == true){
		
		echo '<label>'.$this->l('Title :').'</label>';
		echo '<div class="margin-form">';
		foreach ($languages as $language){
			echo '<div id="title_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">'
				.'<input type="text" size="50" name="title_'.$language['id_lang'].'" value="'.(isset($_POST['title_'.$language['id_lang']]) ? $_POST['title_'.$language['id_lang']] : '').'" />'
				.'</div>';
		}
		$this->displayFlags($languages, $defaultLanguage,$divLangName, 'title');
		echo '</div><div class="clear">&nbsp;</div>';
		
			echo '<label>'.$this->l('Description :').'</label>';
			echo '<div class="margin-form">';
			foreach ($languages as $language){
				echo '<div id="name_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
				 	  <textarea name="desc_'.$language['id_lang'].'" cols="70" rows="2">'.(isset($_POST['desc_'.$language['id_lang']]) ? $_POST['desc_'.$language['id_lang']] : '').'</textarea>
					  </div>';
			}
			$this->displayFlags($languages, $defaultLanguage,$divLangName, 'name');
			echo '</div><div class="clear">&nbsp;</div>';
		}
			echo '<label>'.$this->l('Link :').'</label>
				 <div class="margin-form"> 
				 <input type="text" name="link" size="50" value="'.(isset($_POST['link']) ? $_POST['link'] : 'http://').'">
				 </div>';
				
			echo '<div class="margin-form">
				 <input type="submit" value="'.$this->l('   Save   ').'" name="submitAdd'.$this->table.'" class="button" />
				 </div>';
			echo '</form><hr /></div>';
		}
		
		$i = 0;
		foreach($this->xml->slide as $item){
			echo '<div>
					<label>'.$this->l('Image :').'</label>
					 <div class="margin-form">';
			echo '<a href="'.$currentIndex.'&submitDeleteSlide&token='.$token.'&id_slide='.$i.'" onclick="if(!confirm(\'Etes vous sur de vouloir supprimer ce visuel ?\')) return false;"><img src="../img/admin/delete.gif" alt="delete" align="right" /></a><br />';
			echo '<img src="'.$this->_path.'img/'.$item['img'].'" style="max-width:700px;" />';
			echo '</div>';
			
			echo  '<form name="formUpdateSlide_'.$i.'" action="'.$currentIndex.'&submitUpdateSlide&token='.$token.'&id_slide='.$i.'" method="post" enctype="multipart/form-data">';
		
		if(isset($this->preferences["show_overlay"]) && $this->preferences["show_overlay"] == true){
			
			echo '<label>'.$this->l('Title :').'</label>';
			echo '<div class="margin-form">';
			foreach ($languages as $language){
				$node = $this->xml->xpath("//slide[".($i+1)."]/lang[@name='".$language['iso_code']."']");
				echo '<div id="title_'.$i.'_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">'
				 	.'<input type="text" size="50" name="title_'.$language['id_lang'].'" value="'.(isset($node[0]['title']) ? (string) $node[0]['title'] : '').'" />'
					.'</div>';
			}
			$this->displayFlags($languages, $defaultLanguage,"name_".$i."&curren;title_".$i, 'title_'.$i);
			echo '</div><div class="clear">&nbsp;</div>';
		
			echo '<label>'.$this->l('Description :').'</label>';
			echo '<div class="margin-form">';
			foreach ($languages as $language){
				$node = $this->xml->xpath("//slide[".($i+1)."]/lang[@name='".$language['iso_code']."']");
				echo '<div id="name_'.$i.'_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">'
				 	.'<textarea name="desc_'.$language['id_lang'].'" cols="70" rows="2">'.(isset($node[0]) ? (string) $node[0] : '').'</textarea>'
					.'</div>';
			}
			$this->displayFlags($languages, $defaultLanguage,"name_".$i."&curren;title_".$i, 'name_'.$i);
			echo '</div><div class="clear">&nbsp;</div>';
		}
			
		echo '<label>'.$this->l('Link :').'</label>'
			.'<div class="margin-form">'
			.'<input type="text" name="link" size="50" value="'.$item['link'].'">'
			.'</div>';
				
			echo '<div class="margin-form">'
				 .'<input type="submit" value="'.$this->l('   Save   ').'" name="submitAdd'.$this->table.'" class="button" />'
				 .'</div>';
				
			echo '</form>'
				 .'</div><hr />';
			$i++;	
		}
		
		echo "</fielset>";
		
	}
	
}

?>