<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

// Import library dependencies
jimport('joomla.event.plugin');
// <---------------language Defines ------------------------------------->
define('_SIGPRO_GD_LIBMISSING','<b>Error</b>: GD2 library is not enabled in your server!');
define('_SIGPRO_GD_LIBNOJPG','<b>Error</b>: GD2 library does not support JPG!');
define('_SIGPRO_GD_LIBNOGIF','<b>Error</b>: GD2 library does not support GIF!');
define('_SIGPRO_GD_LIBNOPNG','<b>Error</b>: GD2 library does not support PNG!');
define('_SIGPRO_THUMBERROR','<span>Error creating thumbnail!</span>');
// <--------------- END --------------------------------------------------------->

class plgContentPhotoslideshow extends JPlugin
{
	//Constructor
	function plgPhotoslideshow( &$subject )
	{
		parent::__construct( $subject );
		// load plugin parameters
		$this->_plugin = JPluginHelper::getPlugin( 'content', 'photoslideshow' );
		$this->_params = new JParameter( $this->_plugin->params );
	}
	
	function Resize_File($file, $sourcedir, $max_width = 0, $max_height = 0, $quality = 85){
		$image_type = strstr($file, '.');
		$full_file = $sourcedir.DS.$file;		
		if (eregi("\.png$", $full_file)){
			$img = imagecreatefrompng($full_file);
		}elseif (eregi("\.(jpg|jpeg)$", $full_file)){
			$img = imagecreatefromjpeg($full_file);
		}elseif (eregi("\.gif$", $full_file)){
			$img = imagecreatefromgif($full_file);
		}else{
			echo("Error: Invalid Image Type");
		}
		$FullImage_width = imagesx($img);
		$FullImage_height = imagesy($img);
		
		if (isset($max_width) && isset($max_height) && $max_width != 0 && $max_height != 0){
			$new_width = $max_width;
			$new_height = $max_height;
		}elseif (isset($max_width) && $max_width != 0){
			$new_width = $max_width;
			$new_height = ((int)($new_width * $FullImage_height) / $FullImage_width);
		}elseif (isset($max_height) && $max_height != 0){
			$new_height = $max_height;
			$new_width = ((int)($new_height * $FullImage_width) / $FullImage_height);
		}else{
			$new_height = $FullImage_height;
			$new_width = $FullImage_width;
		}		
		$full_id = imagecreatetruecolor($new_width, $new_height);
		imagecopyresampled($full_id, $img, 0, 0, 0, 0, $new_width, $new_height, $FullImage_width, $FullImage_height);		
		//CREATES THE NAME OF THE SAVED FILE
		$file_name = md5(strtolower($file));
		// Temp folder check
		if (!is_dir($sourcedir.DS.'resized')) { mkdir ($sourcedir.DS.'resized', 0755); }
		if (!is_dir($sourcedir.DS.'resized')) { echo '<div class="message">'.'Could not created the folder'.'</div>'; }
		//CREATES THE PATH TO THE SAVED FILE
		$fullpath = $sourcedir.DS.'resized'.DS. $file_name.$image_type;
		//SAVES IMAGE AND SETS QUALITY || NUMERICAL VALUE = QUALITY ON SCALE OF 1-100
		imagejpeg($full_id, $fullpath, $quality);		
		imagedestroy($full_id);
		unset($max_width);
		unset($max_height);
		
		return $fullpath;
	}


	function onPrepareContent(&$row, &$params, $limitstart) {
 
		// just startup
		global $mainframe;
		$plugin =& JPluginHelper::getPlugin('content', 'photoslideshow');
		$pluginParams = new JParameter( $plugin->params );
		
		// j!1.5 paths
		$mosConfig_absolute_path = JPATH_SITE;
		$mosConfig_live_site = JURI :: base();
		if(substr($mosConfig_live_site, -1)=="/") $mosConfig_live_site = substr($mosConfig_live_site, 0, -1);
		
		// Parameters
		//$type 				= $pluginParams->get('type', 'slideshow');
		$enable_resize 		= $pluginParams->get('resize', 0);
		$_width_ 			= $pluginParams->get('th_width', 200);
		$_height_ 			= $pluginParams->get('th_height', 180);
		$_quality_ 			= $pluginParams->get('th_quality', 85);
		$singlethumb 		= $pluginParams->get('singlethumb', 0);
		$rootfolder 		= $pluginParams->get('rootfolder','/images/stories/');
		$order 				= $pluginParams->get('order','0');
		$autoplay			= $pluginParams->get('autoplay','true');
		$delay				= $pluginParams->get('delay',2000);
		$clickopen 			= $pluginParams->get('clickopen', 'Click to open image!');
		$fadeduration		= $pluginParams->get('fadeduration',500);
		$enable_mootool		= $pluginParams->get('enable_mootool',0);
		$enable_jquery		= $pluginParams->get('enable_jquery',1);
		$singlethumb 		= $pluginParams->get('singlethumb', 0);
	
		// GD2 Library Check
		if(!function_exists("gd_info")) {
			$gdinfo = gd_info();
			$gdsupport = array();
			$version = intval(ereg_replace('[[:alpha:][:space:]()]+', '', $gdinfo['GD Version']));
			if($version!=2) $gdsupport[] = '<div class="message">'._SIGPRO_GD_LIBMISSING.'</div>';
			if (!$gdinfo['JPG Support']) $gdsupport[] = '<div class="message">'._SIGPRO_GD_LIBNOJPG.'</div>';
			if (!$gdinfo['GIF Create Support']) $gdsupport[] = '<div class="message">'._SIGPRO_GD_LIBNOGIF.'</div>';
			if (!$gdinfo['PNG Support']) $gdsupport[] = '<div class="message">'._SIGPRO_GD_LIBNOPNG.'</div>';
			if(count($gd_support)){
				foreach ($gdsupport as $k=>$v) {echo $v;}
			}
		}

		// CHECK IF TEMP FOLDER EXISTS, IF NOT, CREATE IT
		if (preg_match_all("#{jslideshow}(.*?){/jslideshow}#s", $row->text, $matches, PREG_PATTERN_ORDER) > 0) {
			$sigcount = -1;
			foreach ($matches[0] as $match) {
				$sigcount++;
				$_temp = preg_replace("/{.+?}/", "", $match);
				unset($_params);
				$_params = explode(":",$_temp);
				$_images_dir_ = $_params[0];
				if(@$_params[1]) $_width_final_ = $_params[1]; else $_width_final_ = $_width_;
				if(@$_params[2]) $_height_final_ = $_params[2]; else $_height_final_ = $_height_;
				if(isset($_params[3])) $type = $_params[3]; else $type = 'slideshow';
				
				if(@$_params[4]) $_mygallery = $_params[4]; else $_mygallery = 'mygallery';
				
				//create thumbnails for images

				$tempfolder 		= $rootfolder.$_images_dir_.'/resized';
				
				if($enable_resize && !is_dir($mosConfig_absolute_path.$rootfolder.$_images_dir_.'/resized')){
					$path = $mosConfig_absolute_path.$rootfolder.$_images_dir_;
					if ($dh = opendir($path)) {
						while ((@$f = readdir($dh)) !== false) {
							if((substr(strtolower($f),-3) == 'jpg') || (substr(strtolower($f),-3) == 'gif') || (substr(strtolower($f),-3) == 'png')) {
								$images = trim(strtolower($f));
								$this->Resize_File($images, $path, $_width_final_, $_height_final_, $_quality_);
							}
						}
						closedir($dh);
					}
					//end create thumbnails
				}
 				
				unset($images);
				unset($path);
				$noimage = 0;
				if($enable_resize){
					$path = $mosConfig_absolute_path.$rootfolder.$_images_dir_.'/resized';
				}else{
					$path = $mosConfig_absolute_path.$rootfolder.$_images_dir_;
				}
				// read directory				
				if ($dh = opendir($path )) {
					while (($f = readdir($dh)) !== false) {
						if((substr(strtolower($f),-3) == 'jpg') || (substr(strtolower($f),-3) == 'gif') || (substr(strtolower($f),-3) == 'png')) {
							$noimage++;
							$images[] = trim(strtolower($f));
							switch ($order) {
								case 0: sort($images); break;
								case 1: natsort($images); break;
								case 2: natcasesort($images); break;
								case 3: rsort($images); break;
								case 4: shuffle($images); break;
							}
							
							if($noimage == $_howmanythumbs_){
								break;
							}
						}
					}
					closedir($dh);
				}

				// add to the document head
				$sigheader = '';
				if($type == 'slideshow'){
					if($enable_jquery){
						$sigheader .= '<script type="text/javascript" src="'.$mosConfig_live_site.'/plugins/content/photoslideshow/slideshow/jquery-1.js"></script>';
					}
					$sigheader .= '<script type="text/javascript" src="'.$mosConfig_live_site.'/plugins/content/photoslideshow/slideshow/simplegallery.js"></script>';
					$sigheader .= '<style type="text/css" media="all">
						@import "'.$mosConfig_live_site.'/plugins/content/photoslideshow/slideshow/slideshow.css";
					</style>';
					
					if($noimage) { // if exist images
						// add to the document head
						$sigmd5 = $sigcount . '_' . md5($mosConfig_absolute_path.$rootfolder.$_images_dir_);
					}
				}elseif($type == 'slimbox') {
					if($enable_mootool){
						$sigheader .= '<script type="text/javascript" src="'.$mosConfig_live_site.'/plugins/content/photoslideshow/slimbox/mootools.js"></script>';
					}
					$sigheader .= '<script type="text/javascript" src="'.$mosConfig_live_site.'/plugins/content/photoslideshow/slimbox/slimbox.js"></script>
					<style type="text/css" media="all">
						@import "'.$mosConfig_live_site.'/plugins/content/photoslideshow/slimbox/css/slimbox.css";
						#slideshow'.$sigcount . '_' . md5($mosConfig_absolute_path.$rootfolder.$_images_dir_).' a img{border:1px solid #CCCCCC;margin:2px;padding:5px;}
					</style>';
				}					
				$mainframe->addCustomHeadTag($sigheader);

				$itemtitle = preg_replace("/\"/", "'", $row->title);
				if($noimage) { // if exist images
					// add to the document head
					$sigmd5 = $sigcount . '_' . md5($mosConfig_absolute_path.$rootfolder.$_images_dir_);
					// output
					$html = '<div id="slideshow'.$sigmd5.'">';
					if($type == 'slideshow'){
						$sigheader1 .= '<script type="text/javascript">
	
								var '.$_mygallery.' =new simpleGallery({
									wrapperid: "'.$_mygallery.'",
									dimensions: ['.$_width_final_.', '.$_height_final_.'],';
									
							$sigheader1 .= 'imagearray: [';
						//begin loop	
						for($a = 0;$a<$noimage;$a++) { // loop of the images							
							if($images[$a] != '') {	
								$name = substr($images[$a], 0, -4);
								$format = substr($images[$a], -3);
								switch ($format) {
									case 'gif':
										$image_type = 1;
										break;
	
									case 'jpg':
										$image_type = 2;
										break;
	
									case 'png':
										$image_type = 3;
										break;
	
									default:
										$image_type = 2;
										break;
								}
							}
							if($a == ($noimage-1)){
								if($enable_resize)
									$sigheader1 .='["'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/resized/'.$images[$a].'","","",""]';
								else 
									$sigheader1 .='["'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'","","",""]';
							}else{
								if($enable_resize)
									$sigheader1 .='["'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/resized/'.$images[$a].'","","",""],';
								else
									$sigheader1 .='["'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'","","",""],';
							}
						}
						//end loop
							$sigheader1 .='],
									autoplay: ['.$autoplay.', '.$delay.', 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
									persist: false,
									fadeduration: '.$fadeduration.', 
									oninit:function(){
									},
									onslide:function(curslide, i){
									}
								})
								</script>';
							$html .=$sigheader1; 
							$html .= '<div id="'.$_mygallery.'"></div>';
						}else{
							unset($images);
							unset($path);
							$noimage = 0;
							$path = $mosConfig_absolute_path.$rootfolder.$_images_dir_;
							// read directory				
							if ($dh = opendir($path )) {
								while (($f = readdir($dh)) !== false) {
									if((substr(strtolower($f),-3) == 'jpg') || (substr(strtolower($f),-3) == 'gif') || (substr(strtolower($f),-3) == 'png')) {
										$noimage++;
										$images[] = trim(strtolower($f));
										switch ($order) {
											case 0: sort($images); break;
											case 1: natsort($images); break;
											case 2: natcasesort($images); break;
											case 3: rsort($images); break;
											case 4: shuffle($images); break;
										}
									}
								}
								closedir($dh);
							}
						
						
							for($a = 0;$a<$noimage;$a++) { // loop of the images							
								if($images[$a] != '') {	
									$name = substr($images[$a], 0, -4);
									$format = substr($images[$a], -3);
									switch ($format) {
										case 'gif':
											$image_type = 1;
											break;
		
										case 'jpg':
											$image_type = 2;
											break;
		
										case 'png':
											$image_type = 3;
											break;
		
										default:
											$image_type = 2;
											break;
									}
								}
								if(!$enable_resize){
									if($singlethumb){
										$html .= '<a rel="lightbox" href="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'"'. 'title="'.$images[$a].'"';
										$html .= '<img src="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'" />'.'</a>';
									}else{
										if($a ==0){
											$html .= '<a rel="lightbox-'.$_mygallery.'" href="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'"'. 'title="'.$images[$a].'"';
											$html .= '<img src="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'" />'.'</a>';
										}else{
											$html .= '<a style="display:none;" rel="lightbox-'.$_mygallery.'" href="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'"'. 'title="'.$images[$a].'"';
											$html .= '<img src="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'" />'.'</a>';
										}
									}
								}else{
									if($singlethumb){
										$html .= '<a rel="lightbox" href="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'"'. 'title="'.$images[$a].'"';
										$html .= '<img src="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/resized/'.md5($images[$a]).'.'.$format.'" />'.'</a>';
									}else{
										if($a ==0){
											$html .= '<a rel="lightbox-'.$_mygallery.'" href="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'"'. 'title="'.$images[$a].'"';
											$html .= '<img src="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'" /></a>';
										}else{
											$html .= '<a style="display:none;" rel="lightbox-'.$_mygallery.'" href="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'"'. 'title="'.$images[$a].'"';
											$html .= '<img src="'.$mosConfig_live_site.$rootfolder.$_images_dir_.'/'.$images[$a].'" /></a>';
										}
									}
								}
							}
						}	
						$html .= '<small style="display:none;"><a title="website design,website development" href="http://www.joommaster.com">joommaster team</a></small>';
						$html .= '<div stye="clear:both;"></div>';
					}
					$row->text = preg_replace( "#{jslideshow}".$_temp."{/jslideshow}#s", $html , $row->text );
				}
		}
		return true;
	}

}

?>