<?php
/**
 *---------------------------------------------------------------------------------------
 * @package       VirtuePlanet Framework for Joomla!
 *---------------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       Abhishek Das
 * @email         info@virtueplanet.com
 * @link          https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
 */

defined('_JEXEC') or die;

JFormHelper::loadFieldClass('text');

class JFormFieldColormap extends JFormFieldText
{
	protected $type = 'Colormap';

	function getInput()
	{		
		JHtml::_('jquery.framework');
		JHtml::_('script', 'system/html5fallback.js', false, true);
		$doc = JFactory::getDocument();
		$doc->addScript(JUri::root(true) . '/media/vpframework/js/angular.min.js');
		JHtml::_('bootstrap.framework');
		$doc->addScript(JUri::root(true) . '/media/vpframework/js/bootstrap-tagsinput.js');
		$doc->addScript(JUri::root(true) . '/media/vpframework/js/bootstrap-tagsinput-angular.js');
		$doc->addStyleSheet(JUri::root(true) . '/media/vpframework/css/bootstrap-tagsinput.css');
		$doc->addScriptDeclaration("
		jQuery(function($) {
			$('#{$this->id}').tagsinput({
					trimValue: true,
					allowDuplicates: false,
					tagClass: 'label',
					itemText: function(item) {
						var res = item.split(':');
						return res[0] + ':<span class=\"colormap-box\" style=\"background-color: ' + res[1] +'\"></span>';
					}
			});
			$('#{$this->id}').on('beforeItemAdd', function(event) {
				if(event.item.indexOf(':') <= 0 || event.item.match(/:/g).length != 1) {
					alert('Invalid Entry. Please value color mapping in correct format i.e. VALUE:#HEXACOLORCODE. Example: Red:#FF0000');
					event.cancel = true;
					return;
				}
				
				var res = event.item.split(':');
				res[0] = $.trim(res[0]);
				res[1] = $.trim(res[1]);
				var isOk  = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(res[1]);
				
				if(!res || !isOk) {
					alert('Invalid Entry. Please enter valid 3 or 6 digit Hexa Color Code and in correct format i.e. VALUE:#HEXACOLORCODE. Example: Red:#FF0000');
					event.cancel = true;
					return;
				}
				
				event.item = res[0] + ':' + res[1];
			});
		});
		");
		
		$html  = parent::getInput();
		$html .= '<div class="muted small">Examples: Red:#FF0000, Blue:#004986 etc.</div>';
		return $html;
	}
}