<?php
defined('PRODUCT_NAME') or die;
class bxSlider extends ModuleInstance
{
	// Using load() instead of __construct() allows us to access module settings.
	// Potential reproducssions of this are still unknown.
	function load($id)
	{
		parent::load($id);

		$theme 			= $this->setting("lightbox_theme");
		$lightbox		= $this->setting("lightbox");
		$default_link 	= $this->setting("link");
		$this->scripts 	= array();

		// Only include this CSS file if there's going to be a lightbox, otherwise it can conflict with the gallery.
		if($lightbox && $theme)
		{
			$this->scripts = array_merge($this->scripts, array("<link rel=\"stylesheet\" href=\"/modules/slideshow_bxslider/" . $theme . "/colorbox.css\" />"));
		}
		$this->scripts =  array_merge($this->scripts,
                          array("<script async src=\"/modules/slideshow_bxslider/jquery.bxslider.min.js\"></script>",
								"<script async src=\"/modules/slideshow_bxslider/plugins/jquery.easing.1.3.js\"></script>",
								"<script async src=\"/modules/slideshow_bxslider/plugins/jquery.fitvids.js\"></script>",
								"<script async src=\"/modules/slideshow_bxslider/jquery.colorbox-min.js\"></script>"
								));

		$this->enable_jquery = true;
	}

	function render($files = null)
	{
		$module_class 					= $this->setting("module_class");
		$base							= $this->setting("directory");
		$default_link 					= $this->setting("link");
		$lightbox						= $this->setting("lightbox");
		$lightbox_width					= $this->setting("lightbox_width");
		$lightbox_height				= $this->setting("lightbox_height");
		$config_mode 					= $this->setting("mode");
		$config_speed 					= $this->setting("speed");
		$config_slideMargin 			= $this->setting("slideMargin");
		$config_startSlide 				= $this->setting("startSlide");
		$config_randomStart 			= $this->setting("randomStart");
		$config_slideSelector 			= $this->setting("slideSelector");
		$config_infiniteLoop 			= $this->setting("infiniteLoop");
		$config_hideControlOnEnd 		= $this->setting("hideControlOnEnd");
		$config_easing 					= $this->setting("easing");
		$config_captions 				= $this->setting("captions");
		$config_ticker 					= $this->setting("ticker");
		$config_tickerHover 			= $this->setting("tickerHover");
		$config_adaptiveHeight 			= $this->setting("adaptiveHeight");
		$config_adaptiveHeightSpeed 	= $this->setting("adaptiveHeightSpeed");
		$config_video 					= $this->setting("video");
		$config_responsive 				= $this->setting("responsive");
		$config_useCSS 					= $this->setting("useCSS");
		$config_preloadImages 			= $this->setting("preloadImages");
		$config_touchEnabled 			= $this->setting("touchEnabled");
		$config_swipeThreshold 			= $this->setting("swipeThreshold");
		$config_oneToOneTouch 			= $this->setting("oneToOneTouch");
		$config_preventDefaultSwipeX 	= $this->setting("preventDefaultSwipeX");
		$config_preventDefaultSwipeY 	= $this->setting("preventDefaultSwipeY");
		$config_pager 					= $this->setting("pager");
		$config_pagerType 				= $this->setting("pagerType");
		$config_pagerShortSeparator 	= $this->setting("pagerShortSeparator");
		$config_pagerSelector 			= $this->setting("pagerSelector");
		$config_pagerCustom 			= $this->setting("pagerCustom");
		$config_buildPager 				= $this->setting("buildPager");
		$config_controls 				= $this->setting("controls");
		$config_nextText 				= $this->setting("nextText");
		$config_prevText 				= $this->setting("prevText");
		$config_nextSelector 			= $this->setting("nextSelector");
		$config_prevSelector 			= $this->setting("prevSelector");
		$config_autoControls 			= $this->setting("autoControls");
		$config_startText 				= $this->setting("startText");
		$config_stopText 				= $this->setting("stopText");
		$config_autoControlsCombine 	= $this->setting("autoControlsCombine");
		$config_autoControlsSelector 	= $this->setting("autoControlsSelector");
		$config_auto 					= $this->setting("auto");
		$config_pause 					= $this->setting("pause");
		$config_autoStart 				= $this->setting("autoStart");
		$config_autoDirection 			= $this->setting("autoDirection");
		$config_autoHover 				= $this->setting("autoHover");
		$config_autoDelay 				= $this->setting("autoDelay");
		$config_minSlides 				= $this->setting("minSlides");
		$config_maxSlides 				= $this->setting("maxSlides");
		$config_moveSlides 				= $this->setting("moveSlides");
		$config_slideWidth 				= $this->setting("slideWidth");
		$config_slideHeight 			= $this->setting("slideHeight");

		$directory = ABSOLUTE_PATH . "/" . $base;

		if($files == null)
		{
			$files = scandir($directory);
		}
		if(count($files) <= 2)
		{
			return;
		}

		$full_files = array();
		$image_files = array();

		$count = 0;
		foreach($files as $file)
		{
			$full_file = $file;

			if(is_file("$directory/$file") && preg_match('/\.(jpe?g|png|gif|webp)$/i', "$directory/$file"))
			{
				$thumbnail = Mainframe::thumbnail("$directory/$file", $config_slideWidth, $config_slideHeight, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);

				$size 	= @getimagesize(ABSOLUTE_PATH . $thumbnail);
				$width 	= $size[0];
				$height = $size[1];
				$file 	= $thumbnail;
				$full_files[count($image_files)] 	= "/" . $base . "/" . $full_file;
				$image_files[count($image_files)] 	= $file;

				$count ++;
			}
		}
        ?>

		<div id="module_<?php echo($this->module_instance_id); ?>" class="module bxSlider-module <?php echo($module_class); ?>">
			<ul id="slider_<?php echo $this->module_instance_id?>">
				<?php
				for($i=0; $i<count($image_files); $i++)
				{
					$img 		= $image_files[$i];
					$full 		= $full_files[$i];
					$a_name 	= "bxSlider_" . $this->module_instance_id . "_image$i";
					$link 		= $default_link;
					$target 	= "_self";
					$class 		= "";
					$onclick 	= "";

					if($lightbox)
					{
						$class 	= "lightbox";
						$link 	= $full;
					}
					else
					{
						//check if this image should be linked
						for($j=0; $j<20; $j++)
						{
							if(strtolower($this->setting("image$j")) == strtolower(basename($full)))
							{
								$link = $this->setting("link$j");

								if(substr($link, 0, 4) == "http")
								{
									$target = "_blank";
								}
								else
								{
									$target = "_self";
								}

								break;
							}
						}
					}

					if($img)
					{
						// Create a cleaned up version of the file name as a default alt/title.
						$title = str_replace("%20", " ", basename($img));
						//remove file extension
						$title = str_ireplace(array(".jpg", ".jpeg", ".gif", ".png", ".bmp", ".tiff", "/thumbnails/"), "", $title);
						//put a space before all capital letters (camel case)
						$title = preg_replace('/([A-Z][a-z0-9])/', ' $1', $title);
						//remove any thumbnail resizing (100x50) from the end of the filename
						$title = preg_replace('/(_thumb)?_?(\d+)x(\d+)/', '', $title);
						//remove @2x from the end of the filename
						$title = preg_replace('/@2x/', '', $title);
						//replace remaining underscores, dashes, and slashes with spaces
						$title = str_replace(array("_", "/", "\\"), " ", $title);
						$title = trim($title);

						$size = @getimagesize(ABSOLUTE_PATH . "/" . $img);
						$img = str_replace(" ", "%20", $img);

						if($link == "" && !$lightbox)
						{
							$onclick = "onclick='return false;'";
						}
						?><li><a href="<?php echo($link); ?>" <?php echo($onclick); ?> id="<?php echo($a_name); ?>" rel="slider_<?php echo $this->module_instance_id?>" class="<?php echo($class); ?>" target="<?php echo($target); ?>"><img src="<?php echo($img); ?>" data-thumb="<?php echo($img); ?>" width="<?php echo($size[0]); ?>" height="<?php echo($size[1]); ?>" alt="<?php echo($title); ?>" /></a></li><?php
					}
				}
				?>
			</ul>
		</div>

		<script>
			jQuery(window).on("load", function(){
		    	jQuery('#slider_<?php echo $this->module_instance_id?>').bxSlider({
					mode: "<?php echo($config_mode); ?>",
					speed: <?php echo($config_speed); ?>,
					slideMargin: <?php echo($config_slideMargin); ?>,
					startSlide: <?php echo($config_startSlide); ?>,
					randomStart: <?php echo(($config_randomStart == 1 ? "true" : "false")); ?>,
					slideSelector: "<?php echo($config_slideSelector); ?>",
					infiniteLoop: <?php echo(($config_infiniteLoop == 1 ? "true" : "false")); ?>,
					hideControlOnEnd: <?php echo(($config_hideControlOnEnd == 1 ? "true" : "false")); ?>,
					easing: "<?php echo($config_easing); ?>",
					captions: <?php echo(($config_captions == 1 ? "true" : "false")); ?>,
					ticker: <?php echo(($config_ticker == 1 ? "true" : "false")); ?>,
					tickerHover: <?php echo(($config_tickerHover == 1 ? "true" : "false")); ?>,
					adaptiveHeight: <?php echo(($config_adaptiveHeight == 1 ? "true" : "false")); ?>,
					adaptiveHeightSpeed: <?php echo($config_adaptiveHeightSpeed); ?>,
					video: <?php echo(($config_video == 1 ? "true" : "false")); ?>,
					responsive: <?php echo(($config_responsive == 1 ? "true" : "false")); ?>,
					useCSS: <?php echo(($config_useCSS == 1 ? "true" : "false")); ?>,
					preloadImages: "<?php echo($config_preloadImages); ?>",
					touchEnabled: <?php echo(($config_touchEnabled == 1 ? "true" : "false")); ?>,
					swipeThreshold: <?php echo($config_swipeThreshold); ?>,
					oneToOneTouch: <?php echo(($config_oneToOneTouch == 1 ? "true" : "false")); ?>,
					preventDefaultSwipeX: <?php echo(($config_preventDefaultSwipeX == 1 ? "true" : "false")); ?>,
					preventDefaultSwipeY: <?php echo(($config_preventDefaultSwipeY == 1 ? "true" : "false")); ?>,
					pager: <?php echo(($config_pager == 1 ? "true" : "false")); ?>,
					pagerType: "<?php echo($config_pagerType); ?>",
					pagerShortSeparator: "<?php echo($config_pagerShortSeparator); ?>",
					pagerSelector: "<?php echo($config_pagerSelector); ?>",
					pagerCustom: "<?php echo($config_pagerCustom); ?>",
					buildPager: "<?php echo($config_buildPager); ?>",
					controls: <?php echo(($config_controls == 1 ? "true" : "false")); ?>,
					nextText: "<?php echo($config_nextText); ?>",
					prevText: "<?php echo($config_prevText); ?>",
					nextSelector: "<?php echo($config_nextSelector); ?>",
					prevSelector: "<?php echo($config_prevSelector); ?>",
					autoControls: <?php echo(($config_autoControls == 1 ? "true" : "false")); ?>,
					startText: "<?php echo($config_startText); ?>",
					stopText: "<?php echo($config_stopText); ?>",
					autoControlsCombine: <?php echo(($config_autoControlsCombine == 1 ? "true" : "false")); ?>,
					autoControlsSelector: "<?php echo($config_autoControlsSelector); ?>",
					auto: <?php echo(($config_auto == 1 ? "true" : "false")); ?>,
					pause: <?php echo($config_pause); ?>,
					autoStart: <?php echo(($config_autoStart == 1 ? "true" : "false")); ?>,
					autoDirection: "<?php echo($config_autoDirection); ?>",
					autoHover: <?php echo(($config_autoHover == 1 ? "true" : "false")); ?>,
					autoDelay: <?php echo($config_autoDelay); ?>,
					minSlides: <?php echo($config_minSlides); ?>,
					maxSlides: <?php echo($config_maxSlides); ?>,
					moveSlides: <?php echo($config_moveSlides); ?>,
					slideWidth: <?php echo($config_slideWidth); ?>
				});

				<?php
				// Only include this JS if there's going to be a lightbox, otherwise it can conflict with the gallery.
				if($lightbox)
				{
					?>
					jQuery("a.lightbox").colorbox({
						'rel'			: 'slider_<?php echo $this->module_instance_id?>',
						'transition'	: 'elastic',
						'current'		: '{current}/{total}',
						'scalePhotos' 	: true,
						'width'			: '<?php echo($lightbox_width); ?>',
						'height'		: '<?php echo($lightbox_height); ?>',
						'maxWidth' 		: '100%',
						'maxHeight'		: '100%'
					});
					<?php
				}
				?>
			});
	    </script>
		<?php
	}
}
