<?php
/**
 * @package     Cherry Picker for Virtuemart
 * @subpackage  Link Template
 * @author		Maksym Stefanhuck
 * @copyright   Copyright (C) 2009 - 2014 Galt.md. All rights reserved.
 * @license     GNU General Public License version 2 or later; see COPYING.txt
 */

namespace cherrypicker;
defined('_JEXEC') or die;

use \JFactory;
use \JHtml;
use \JText;
use \JRequest;


$doc = JFactory::getDocument();
//$config = CherryPicker::contextModule()->config();
//$module_id = CherryPicker::contextModule()->id();
$config = \CPFactory::getConfiguration();
$module_id = $config->get('module_id');
$translate = $config->get('translate');
$units = $this->units();
$selecttype = $this->option('selecttype');
$showCount = $this->option('show_count');
$hasCount = ($showCount || $this->option('show_empty_values'));
$hide = $this->option('hide');
$selected_values_ontop = $this->option('selected_values_ontop');
$uniqueId = $this->uniqueViewId();


//$path_only = true;
//$override = JHtml::stylesheet('mod_cherry_picker/link.css', false, true, $path_only);
////var_dump($override);
//if ($override)
//	JHtml::stylesheet('mod_cherry_picker/link.css', false, true, false);
//else
//	JHtml::stylesheet('modules/mod_cherry_picker/css/link.css');

$this->addStylesheet('common.css');
$this->addStylesheet('link.css');

$this->addScript('helper.js');
//if ($this->option('quickrefine'))
	//$this->addScript('quickrefine.js');
$this->addScript('updater.js');

//JHtml::script('modules/mod_cherry_picker/js/helper.js');
//if ($this->option('quickrefine'))
//	JHtml::script('modules/mod_cherry_picker/js/quickrefine.js');
//JHtml::script('modules/mod_cherry_picker/js/updater.js');



$selectedValues = $this->selectedValues();
if ($selecttype == 'single' && $selectedValues)
	$availableValues = array();
else
	$availableValues = $this->availableValues();


$display = JRequest::getVar('display', '');
//$ajax_request = $config->get('ajax_request');
$limit = $this->option('seemore_size');
$use_seemore = false;
if ($hide == CP_HIDE_SEEMORE && $limit && count($availableValues) > $limit) {
	$use_seemore = true;
	$seemore_should_display = true;
	//$seemore_ajax = ($this->option('seemore_ajax') && !$config->get('ajax_request'));
	$seemore_ajax = ($this->option('seemore_ajax') && $display != 'seemore');
	$seemore_anchor = $this->option('seemore_anchor');

	$more_text = '<span class="cp-link-seemore-indicator">&#xe605;</span>'
		.' <span class="cp-link-seemore-text">'
		. JText::_($config->get('string_seemore', 'CP_SEEMORE'))
		.'</span>';
	$less_text = '<span class="cp-link-seemore-indicator">&#xe606;</span>'
		.' <span class="cp-link-seemore-text">'
		. JText::_($config->get('string_seeless', 'CP_SEELESS'))
		.'</span>';

	$seemore_html = '<div class="cp-link-seemore" id="'. $uniqueId .'_seemore_handle">';
	$seemore_html .= $more_text;
	$seemore_html .= '</div>';

} else if ($hide == CP_HIDE_SCROLL) {
	$height = $this->option('scroll_size', 100);
}



//echo '<pre>';
//print_r($availableValues);
//echo '</pre>';
echo '<div id="'. $uniqueId .'_group" class="cp-link-box">';

if ($hide == CP_HIDE_SCROLL)
	echo '<div class="cp-scroll-box" style="max-height:'. $height .'px">';

if ($selecttype == 'single' && $selectedValues) {
	$div = html::tag('div');
	$back = html::tag('a')->href($this->removeValuesUrl())
				->attr('class', 'cp-link-clear')
				->html( '&lsaquo; '. JText::_($config->get('string_back', 'CP_BACK')) )
				->appendTo($div);

	$div2 = html::tag('div');
	$span = html::tag('span')->attr('class', 'cp-link-selected-values')
				->appendTo($div2);

	foreach ($selectedValues as $value) {
		$text = $translate ? JText::_($value['name']) : $value['name'];
		if ($units) $text .= $units;
		if ($this->showValueImage() && ($value['thumb'] || $value['image'])) {
			html::tag('image')
				->attr('class', 'cp-link-value-image')
				->attr('src', ($value['thumb'] ? $value['thumb'] : $value['image']))
				->attr('title', $text)
				->appendTo($span);
			//html::tag('br')->appendTo($a);
		}
		if ($this->showValueText())
			html::tag('span')
				->attr('class', 'cp-link-value-text')
				->html($text)
				->appendTo($span);
	}
	//$selectedValueNames = array_map(function($v) {
	//	return $v['name'];
	//}, $selectedValues);
	//if ($translate) {
	//	$values = array_map(function($v) {
	//		return JText::_($v);
	//	}, $selectedValueNames);
	//	$span->html( join(', ', $values) );
	//} else {
	//	$span->html( join(', ', $selectedValueNames) );
	//}

	echo $div;
	echo $div2;

} else {
	if ($this->option('show_clear_link') && $selectedValues) {
		$div = html::tag('div');
		$a = html::tag('a')->href($this->removeValuesUrl())
				->attr('class', 'cp-link-clear')
				->html( JText::_($config->get('string_clear_selection', 'CP_CLEAR_SELECTION')) )
				->appendTo($div);
		echo $div;
	}

	$list_class = 'cp-link-list';
	if ( ($columns = $this->option('columns')) && $columns > 1)
		$list_class .= ' cp-columns-'. $columns;
	echo '<ul class="'. $list_class .'">';

	//if ($this->option('show_clear_link') && $selectedValues) {
	//	$li = html::tag('li');
	//	$a = html::tag('a')->href($this->removeValuesUrl())
	//			->attr('class', 'cp-link-clear')
	//			->html( JText::_($config->get('string_clear_selection', 'CP_CLEAR_SELECTION')) )
	//			->appendTo($li);
	//	echo $li;
	//}

	foreach ($availableValues as $i => $value) {
		//$selected = in_array($value['name'], $selectedValues);

		/*
		 * If selected values should go on top of the list we delay See more..
		 * until all such values are displayed.
		 */
		if ($use_seemore && $seemore_should_display && $i >= $limit && !($selected_values_ontop && $value['selected'])) {
			$seemore_should_display = false;
			echo '</ul>';
			if ($this->option('seemore_anchor') == 'top')
				echo $seemore_html;

			echo '<ul class="'. $list_class .'" id="'. $uniqueId .'_seemore_content" style="display:none">';
			if ($seemore_ajax)
				break;
		}


		$text = $translate ? JText::_($value['name']) : $value['name'];
		if ($units)
			$text .= $units;

		$li = html::tag('li');
		$a = html::tag('a')
				->href($value['url'])
				->attr('class', 'cp-link-value')
				->attr('data', htmlentities($value['alias'], ENT_QUOTES, "UTF-8"))
				->appendTo($li);
		if ($value['selected']) $a->addClass('cp-link-value-selected');
		if ($hasCount && $value['count'] === 0) $a->addClass('cp-link-value-disabled');

		if ($selecttype != 'single')
			html::tag('span')->attr('class', 'cp-link-value-tick')->appendTo($a);

		if ($this->showValueImage() && ($value['thumb'] || $value['image'])) {
			html::tag('image')
				->attr('class', 'cp-link-value-image')
				->attr('src', ($value['thumb'] ? $value['thumb'] : $value['image']))
				->attr('title', $text)
				->appendTo($a);
			//html::tag('br')->appendTo($a);
		}
		if ($this->showValueText())
			html::tag('span')
				->attr('class', 'cp-link-value-text')
				->html($text)
				->appendTo($a);

		if ($showCount && $value['count'] !== '')
			html::tag('span')
				->attr('class', 'cp-link-value-count')
				->html('('. $value['count'] .')')->appendTo($a);

		echo $li;
	}

	echo '</ul>';
	if ($use_seemore && $this->option('seemore_anchor') == 'bottom')
		echo $seemore_html;

}


if ($hide == CP_HIDE_SCROLL)
	echo '</div>';

echo '</div>';


/*

	Notes:

	#1 When the page initially loads Cherry Picker may be without link
		subviews. As a result no resources (e.g. link.css) will be loaded.
		Then user navigates to other category, module will update itself
		with Ajax and some link subviews may be displayed.
		But since resources haven't been loaded previously by php the display
		will appear broken.
		Use javascript to load resource if it hasn't been loaded already.


*/

?>
<script>
<?php

	if ($use_seemore && $display != 'seemore') {

?>
jQuery(function($) {
	CherryPicker.new("seemore", {
		handle: '#<?php echo $uniqueId .'_seemore_handle' ?>',
		content: '#<?php echo $uniqueId .'_seemore_content' ?>',
		moreText: '<?php echo addslashes($more_text) ?>',
		lessText: '<?php echo addslashes($less_text) ?>'
<?php

	if ($seemore_ajax) {

?>
		, load: {
			view: '<?php echo $this->displayName() ?>',
			part: '<?php echo $this->name() ?>'
		}
<?php

	}

?>
	});
});
<?php

}

?>
jQuery(function($) {
	var multimodule_isolated_mode = <?php echo CP_MULTIMODULE_ISOLATED_MODE ?>;
	var ignore_category = <?php echo (int)$config->get('category_ignored_by_others') ?>;
	var selectedValues = [<?php
		foreach ($selectedValues as $i => $value) {
			if ($i != 0) echo ", ";
			echo '{';
			echo 'name: "'. addslashes($value['name']) .'",';
			echo 'alias: "'. addslashes($value['alias']) .'",';
			echo 'url: "'. addslashes($this->removeValueUrl($value)) .'"';
			echo '}';
		}
	?>];
	var selectedValueNames = selectedValues.map(function(v) { return v.name });
	var selectedValueAliases = selectedValues.map(function(v) { return v.alias });

	var module = CherryPicker.module.makeContext(<?php echo $module_id ?>);
	var submodule = CherryPicker.new("submodule", {
		name: "<?php echo $this->name() ?>",
		urlname: "<?php echo $this->urlname() ?>",
		selectedValues: selectedValueAliases,
		selecttype: "<?php echo $this->option('selecttype') ?>"
	});
	if (( submodule_old = module.submodules(submodule.name())[0] ))
		module.replaceSubmodule(submodule_old, submodule);
	else
		module.addSubmodule(submodule);

	// Note #1
	CherryPicker.loadResource('link.css', 'css');


	function getData() {
		var data = [],
			s;

		if (! multimodule_isolated_mode) {
			var has_manufacturer = module.submodules('manufacturer').length;
			var has_category = module.submodules('category').length;
			var modules = CherryPicker.module.modules;
			for (var i = 0; i < modules.length; ++i)
				if (modules[i] != module) {
					var exclude = [];
					if (has_manufacturer && ( manufacturer = modules[i].submodules('manufacturer')[0] ))
						exclude.push(manufacturer);
					if (has_category && ( category = modules[i].submodules('category')[0] ))
						exclude.push(category);
					s = modules[i].toString({
						exclude_submodules: exclude,
						urlencode: true,
						originalState: true
					});
					if (s) data.push(s);
				}
		}

		var exclude = [submodule];
		if (ignore_category && ( category = module.submodules('category')[0] ))
			exclude.push(category);

		s = module.toString({
			exclude_submodules: exclude,
			urlencode: true,
			originalState: true
		});
		if (s) data.push(s);

		s = submodule.toString({urlencode: true});
		if (s) data.push(s);
		return data.join('&');
	}


<?php

	if ($this->option('quickrefine') && $display != 'seemore') {

?>
	var quickrefine = CherryPicker.new("quickrefine", {
		content: $("#<?php echo $uniqueId ?>_group"),
		// elements could be added dynamically with ajax, so in this case provide their selector
		displayElements: "#<?php echo $uniqueId ?>_group .cp-link-list > li",
		dataElements: "#<?php echo $uniqueId ?>_group .cp-link-value-text",
		values: selectedValueNames,
<?php
		if ($units) {

?>
		units: "<?php echo addslashes($units) ?>",
<?php

		}

?>
		hideStyle: "<?php echo $this->option('quickrefine_hidestyle') ?>",
		string: {
			removeSelected: '<?php echo addslashes(JText::_($config->get('string_quickrefine_remove_selected', 'CP_QUICKREFINE_REMOVE_SELECTED'))) ?>'
		},
		removeValue: function(name) {
			name = name.replace('&amp;', '&', 'g');
			var value = selectedValues.filter(function(v) { return v.name == name})[0];
			if (value) {
				submodule.removeSelectedValue(value.alias);
				var url = value.url.replace('&amp;', '&', 'g');
				if (typeof runUpdates != "undefined") {
					runUpdates({
						url: url
					});
				} else {
					window.location = url;
				}
			}

		}
	});
<?php

	}


	$update_products = $this->option('onselect_update_products');
	$update_filters = $this->option('onselect_update_filters');
	if ($display != 'seemore' && ($update_products || $update_filters)) {
?>
	var update_products = <?php echo $update_products ?>;
	var update_filters = <?php echo $update_filters ?>;
	$("#<?php echo $uniqueId ?>_group").on("click", ".cp-link-value", function(event) {
		event.preventDefault();
		var $this = $(this);
		if (! $this.attr('href'))
			return;

		var value = $this.attr('data');
		if (submodule.isSelected(value)) {
			submodule.removeSelectedValue(value);
		} else if (submodule.selecttype() == 'multi') {
			submodule.addSelectedValue(value);
		} else {
			submodule.selectedValues([value]);
		}

		runUpdates({
			url: $this.attr('href'),
			target: this
		});
	});

	$("#<?php echo $uniqueId ?>_group .cp-link-clear").click(function(event) {
		event.preventDefault();
		submodule.selectedValues('');
		runUpdates({
			url: $(this).attr('href'),
			target: this
		});
	});

	function runUpdates(options) {
		var defaults = {
			url: '',
			target: null
		};
		options = $.extend({}, defaults, options);

		var data = getData();
		var updater = CherryPicker.updater;
		if (update_filters) {
			updater.updateModule({
				content: module.content(),
				data: 'module_id=' + module.id() + '&' + data,
				//showLoader: true
				loader: {
					relativeTo: options.target
				}
			});
		}

		if (update_products) {
			updater.updateProducts({
				content: $("#main"),
				url: options.url,
				showLoader: true,
				data: data,
				module_id: module.id(),
				triggerUpdateEvent: update_filters
			});
		}
	}


<?php

	}

?>

});
</script>
