<?php

/**
 * @copyright	Copyright (C) 2015 Cédric KEIFLIN alias ced1870
 * https://www.joomlack.fr
 * https://www.template-creator.com
 * @license		GNU/GPL
 * */
defined('_JEXEC') or die('Restricted access');
jimport('joomla.event.plugin');

class plgSystemScrolltock extends JPlugin {

	function __construct(&$subject, $params) {
		parent::__construct($subject, $params);
	}

	public function onBeforeRender() {
		$app = JFactory::getApplication();

		// si pas en frontend, on sort
		if ($app->isClient('administrator')) {
			return false;
		}

		$doc = JFactory::getDocument();
		$doctype = $doc->getType();
		$input = new JInput();

		// not for popup
		if ($input->get('tmpl') == 'component') {
			return;
		}

		// si pas HTML, on sort
		if ($doctype !== 'html') {
			return;
		}

		if (version_compare(JVERSION, '3') >= 1 ) { 
			JHTML::_('jquery.framework', true);
		} else {
//			$jquerycall = "\n\t<script src=\"" . JURI::base(true) . "/plugins/system/scrolltock/assets/jquery.min.js\" type=\"text/javascript\"></script>";
		}

//		$doc->addStyleSheet(JURI::base(true) . "/plugins/system/scrolltock/assets/scrolltock.css");
		// charge les paramètres par défaut
		$this->loadLanguage();
		$plugin = JPluginHelper::getPlugin('system', 'scrolltock');
		$pluginParams = new JRegistry($plugin->params);
		$fxduration = $pluginParams->get('fxduration', '1000');
		$offsety = $pluginParams->get('offsety', '0');
		$activatetotop = $pluginParams->get('activatetotop', '1');
		$totop_startoffset = $pluginParams->get('totop_startoffset', '100');
		$totop_text =  $pluginParams->get('totop_showtext', '0') == '1' ? JText::_('PLG_SCROLLTOCK_SCROLL_TO_TOP') : '';
		$mobile_resolution = $pluginParams->get('mobile_resolution', '0');
		$mobile_offsety = $pluginParams->get('mobile_offsety', '0');
		$keephash = $pluginParams->get('keephash', '0', 'int');

		// for the scroll to top button
		$scrolltotop = "$(document.body).append('<a href=\"#\" class=\"scrollToTop\" role=\"button\" aria-label=\"" . addslashes(JText::_('PLG_SCROLLTOCK_SCROLL_TO_TOP')) . "\"><span class=\"scrollToTop-icon\"></span><span class=\"scrollToTop-text\">" . $totop_text . "</span></a>');
					//Check to see if the window is top if not then display button
					$(window).scroll(function(){
						if ($(this).scrollTop() > " . (int) $totop_startoffset . ") {
							$('.scrollToTop').addClass('scrolltotop-show');
						} else {
							$('.scrollToTop').removeClass('scrolltotop-show');
						}
					});

					//Click event to scroll to top
					$('.scrollToTop').click(function(){
						$('html, body').animate({scrollTop : 0},". (int) $fxduration . ");
						return false;
					});";

		// add the script
		$js = "\n\tvar Scrolltock = function(container) {
				if (! container) container = jQuery(document);
				jQuery('a.scrollTo', container).click( function(event) {
					var pageurl = window.location.href.split('#');
					var linkurl = jQuery(this).attr('href').split('#');

					if ( jQuery(this).attr('href').indexOf('#') != 0
						&& ( ( jQuery(this).attr('href').indexOf('http') == 0 && pageurl[0] != linkurl[0] )
						|| jQuery(this).attr('href').indexOf('http') != 0 && pageurl[0] != '" . JUri::base() . "' + linkurl[0].replace('" . JUri::base(true) . "/', '') )
						) {
						// here action is the natural redirection of the link to the page
					} else {
						" . ($keephash == '1' ? '' : 'event.preventDefault();') . "
						jQuery(this).scrolltock();
						setTimeout(function(){ jQuery(this).scrolltock(); }, 1000); // add timer to fix issue with page load
					}
				});
			}
			jQuery(document).ready(function($){";
		if ($activatetotop) {
			$js .= $scrolltotop;
		}
		$js .= "
				Scrolltock();

				$.fn.scrolltock = function() {
					var link = $(this);
					var page = jQuery(this).attr('href');
					if (page === undefined) return;
					var pattern = /#(.*)/;
					var targetEl = page.match(pattern);
					if (! targetEl.length) return;
					if (! jQuery(targetEl[0]).length) return;

					// close the menu hamburger
					if (link.parents('ul.nav,ul.menu,ul.maximenuck').length) {
						var menu = $(link.parents('ul.nav,ul.menu,ul.maximenuck')[0]);
						if (menu.parent().find('> .mobileckhambuger_toggler').length && menu.parent().find('> .mobileckhambuger_toggler').attr('checked') == 'checked') {
							menu.animate({'opacity' : '0'}, function() { menu.parent().find('> .mobileckhambuger_toggler').attr('checked', false); menu.css('opacity', '1'); });
						}
					}

					var speed = link.attr('data-speed') ? link.attr('data-speed') : ". (int) $fxduration . ";
					var isMobile = ($(window).width() <= " . (int)$mobile_resolution . ");
					if (isMobile) {
						var offsety = link.attr('data-mobile-offset') ? parseInt(link.attr('data-mobile-offset')) : ". (int) $mobile_offsety . ";
					} else {
						var offsety = link.attr('data-offset') ? parseInt(link.attr('data-offset')) : ". (int) $offsety . ";
					}
					jQuery('html, body').animate( { scrollTop: jQuery(targetEl[0]).offset().top + offsety }, speed, scrolltock_setActiveItem() );
					return false;
				}
				// Cache selectors
				var lastId,
				baseItems = jQuery('a.scrollTo');
				// Anchors corresponding to menu items
				scrollItems = baseItems.map(function(){
					// if (! jQuery(jQuery(this).attr('href')).length) return;
					var pattern = /#(.*)/;
					var targetEl = jQuery(this).attr('href').match(pattern);

						if (targetEl == null ) return;
						if (! targetEl[0]) return;
						if (! jQuery(targetEl[0]).length) return;
						var item = jQuery(targetEl[0]);
					if (item.length) { return item; }
				});
				// Bind to scroll
				jQuery(window).scroll(function(){
					scrolltock_setActiveItem();
				});
				
				function scrolltock_setActiveItem() {
					var isMobile = ($(window).width() <= " . (int)$mobile_resolution . ");
					if (isMobile) {
						var offsety = ". (int) $mobile_offsety . ";
					} else {
						var offsety = ". (int) $offsety . ";
					}
					// Get container scroll position
					var fromTop = jQuery(this).scrollTop()- (offsety) + 2;

					// Get id of current scroll item
					var cur = scrollItems.map(function(){
						if (jQuery(this).offset().top < fromTop)
							return this;
					});
					if (cur.length) {
						// Get the id of the current element
						cur = cur[cur.length-1];
						var id = cur && cur.length ? cur[0].id : '';
						var targetParent = baseItems.end().filter('[href$=\"#'+id+'\"]').parent();

						if (lastId !== id || !targetParent.hasClass('active')) {
						   lastId = id;
						   // Set/remove active class
							baseItems.parent().parent().find('.active').removeClass('active');
							baseItems
							 .parent().removeClass('active')
							 .end().filter('[href$=\"#'+id+'\"]').parent().addClass('active');
						}
					} else {
						baseItems.parent().parent().find('.active').removeClass('active');
						baseItems.parent().removeClass('active');
					}                  
				}
			}); // end of dom ready

			window.addEventListener(\"load\", function(event) {

				var pageurl, pattern, targetPage;
				pageurl = window.location.href;
				pattern = /#(.*)/;
				targetPage = pageurl.match(pattern);

				var scrolltock_animate = function() {
					jQuery('html, body').animate( { scrollTop: jQuery(targetPage[0]).offset().top + ". (int) $offsety . " }, ". (int) $fxduration . " );
				}
				if (targetPage && jQuery(targetPage[0]).length) {
					" . ($keephash == '0' ? '' : 'scrolltock_removeHashFromUrl();') . "
					scrolltock_animate();
					setTimeout(function(){ scrolltock_animate(); }, 1000);
				}
			});

			function scrolltock_removeHashFromUrl() {
				var uri = window.location.toString();
	  
				if (uri.indexOf(\"#\") > 0) {
					var clean_uri = uri.substring(0,
									uri.indexOf(\"#\"));
	  
					window.history.replaceState({},
							document.title, clean_uri);
				}
			}
			";

		$doc->addScriptDeclaration($js);
		
		$css= $this->addCss();
		$doc->addStyleDeclaration($css);

		return;
	}

	private function addCss() {
		$plugin = JPluginHelper::getPlugin('system', 'scrolltock');
		$pluginParams = new JRegistry($plugin->params);

		$css = '.scrollToTop {
			padding: ' . $this->testUnit($pluginParams->get('totop_padding', '10px')) . ';
			margin: ' . $this->testUnit($pluginParams->get('totop_margin', '20px')) . ';
			text-align: center; 
			font-weight: bold;
			text-decoration: none;
			position:fixed;
			bottom: 0;
			right: 0;
			opacity: 0;
			transition: opacity 0.2s ease;
			z-index: 100;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			width: ' . $this->testUnit($pluginParams->get('totop_width', '50px')) . ';
			height: ' . $this->testUnit($pluginParams->get('totop_height', '50px')) . ';
			color: ' . $pluginParams->get('totop_color', 'inherit') . ';
			font-size: ' . $this->testUnit($pluginParams->get('totop_fontsize', 'inherit')) . ';
			font-family: ' . $pluginParams->get('totop_fontfamily', 'inherit') . ';
			background-color: ' . $pluginParams->get('totop_backgroundcolor', 'none') . ';
			background-image: url(' . JUri::root(true) . '/' . $pluginParams->get('totop_backgroundimage', '') . ');
			background-position: center center ;
			background-repeat: no-repeat;
			border: ' . $this->testUnit($pluginParams->get('totop_borderwidth', '2')) . ' ' . $pluginParams->get('totop_bordercolor', 'rgba(0,0,0,0.2)') . ' solid;
			border-radius: ' . $this->testUnit($pluginParams->get('totop_borderradius', '50%')) . ';
			box-shadow: ' . $pluginParams->get('totop_shadowcolor', 'transparent') . ' 0 0 ' . $this->testUnit($pluginParams->get('totop_shadowwidth', '0')) . ';
		}
		.scrollToTop:hover {
			text-decoration:none;
			color: ' . $pluginParams->get('totop_hovercolor', '') . ';
		}';

		$css .= '.scrollToTop-icon {
				display: inline-block;
				vertical-align: middle;
				background-image: url(' . JUri::root(true) . '/' . $pluginParams->get('totop_arrowimage', 'plugins/system/scrolltock/images/arrow-4.svg') . ');
				background-position: center center ;
				background-repeat: no-repeat;
				background-size: 20px 20px;
				width: ' . $this->testUnit($pluginParams->get('totop_arrow_width', '100%')) . ';
				height: ' . $this->testUnit($pluginParams->get('totop_arrow_height', '100%')) . ';
				margin: ' . $this->testUnit($pluginParams->get('totop_arrow_margin', '0')) . ';
				border: ' . ((int)$pluginParams->get('totop_arrow_borderwidth', '') > 0 ? $this->testUnit($pluginParams->get('totop_arrow_borderwidth', '')) . ' solid ' . $pluginParams->get('totop_arrow_bordercolor', 'rgba(0,0,0,0.2)') . ';' : '') . '
				border-radius: ' . $this->testUnit($pluginParams->get('totop_arrow_borderradius', '')) . ';
			}
			.scrollToTop-text {
				vertical-align: middle;
				display: block;
			}';
	
		if ($pluginParams->get('totop_hideresolution')) {
			$css .= '@media only screen and (max-width:' . $this->testUnit($pluginParams->get('totop_hideresolution')) . '){'
					. '.scrollToTop {display: none !important;}'
					. '}';
		}

		$css .= '.scrolltotop-show { opacity: ' . $pluginParams->get('totop_opacity', '1') . '; }';

		return $css;
	}

	/**
	 * Test if there is already a unit, else add the px
	 *
	 * @param string $value
	 * @return string
	 */
	public static function testUnit($value) {
		if ((stristr($value, 'px')) OR (stristr($value, 'em')) OR (stristr($value, '%')) OR (stristr($value, 'auto')) ) {
			return $value;
		}

		if ($value == '') {
			$value = 0;
		}

		return $value . 'px';
	}
}